简体   繁体   中英

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>

在循环中,在打印之前:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM