简体   繁体   English

在Perl中使用chomp()

[英]chomp() usage in Perl

I have an XML file. 我有一个XML文件。 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. 我尝试了chomp()方法,发现它将删除所有新的线符号。 I still need to output the standard XML file format. 我仍然需要输出标准XML文件格式。

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. 老实说,我不建议使用chomp来做到这一点,而只是使用解析器来解析和重新格式化XML。

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

This reads, validates your XML and reformats the output. 这将读取,验证您的XML并重新格式化输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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