chomp() usage in Perl

I have an XML file. There is some blank line in the file. How can I remove only the blank lines? I tried chomp() method and found that it will remove all the new line symbols. I still need to output the standard XML file format.

while(my $line = <$fh>) {

        #chomp($line);
        #$line =~ s/\s+//g;
        print $line;
}

__DATA__
    <item>

      <key>AB</key>

      <info>

        <format>10</format>

        <description>Any binary string</description>

        <value>NA</value>

        <whereUsed>A2B25,A2B26</whereUsed>

      </info>

    </item>

The output form below expected.

<item>
  <key>AB</key>
  <info>
    <format>10</format>
    <description>Any binary string</description>
    <value>NA</value>
    <whereUsed>A2B25,A2B26</whereUsed>
  </info>
</item>

Answers


In your loop, before the print:

next unless $line =~ /\S/;

You can print the line only if it has a non-space character:

while(my $line = <DATA>) {
        print $line if ($line=~/\S/);
}

I honestly wouldn't recommend doing this with chomp and instead just parse and reformat your XML using a parser.

use XML::Twig;
XML::Twig->new( 'pretty_print' => 'indented_a' )->parse( \*DATA )->print;

This reads, validates your XML and reformats the output.


Need Your Help

Why is my code returning it's results in quotes?

javascript html

My code is returning all of it's results within quotes. So it appears as if it is raw html. an example of the code running can be found here

Parse Json String (Feed RSS file) in Android

java android json parsing

How can I parse this piece of JSON code?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.