Perl:擦除空行并保存在新文件中

时间:2013-01-16 18:39:27

标签: perl counter erase string

我正在尝试编写一个脚本,该脚本将对文件中的空行进行计数和擦除,并将更改保存在新文件中:

if (@ARGV != 2) {
  print "Usage: $0 infile outfile\n";
  exit;
}
$infile = @ARGV[0];
$outfile = @ARGV[1];
open($old, "<$infile");
open($new, ">$outfile");
@mass = <$old>;
foreach $newc(@mass) {
    $counter++;
    if ($_ =~ /^$/) {
        print "blank line found in $old at line number $counter\n";
        print $new;
    }
}
close($new);
close($old);

但它不起作用。我哪里错了?

5 个答案:

答案 0 :(得分:4)

这是另一种选择:

use strict;
use warnings;

@ARGV == 2 or die "Usage: $0 infile outfile\n";

open my $fhIN,  '<', $ARGV[0] or die $!;
open my $fhOUT, '>', $ARGV[1] or die $!;

while (<$fhIN>) {
    if (/\S/) {
        print $fhOUT $_;
    }
    else {
        print "Blank at line $.\n";
    }
}

amon所示,您可以迭代文件的行,而无需先将它们读入数组。此脚本还利用$.,其中包含文件的当前行号。正则表达式/\S/检查行中的任何非空白字符,因为这表示非空白行。如果/\S/为真,则将该行写入outfile,否则会打印空白行通知。

文件句柄在词法范围内the three-argument form of open(首选方法),因此文件将在脚本结束时自动close


您甚至可以更进一步,利用STDIN,STDOUT和STDERR获得最大的灵活性和实用性。

use strict;
use warnings;

while (<>) {
    if (/\S/) {
        print;
    }
    else {
        print STDERRR "Blank at line $.\n";
    }
}

然后使用

script.pl file.in >file.out

而不是

script.pl file.in file.out

但它也允许你做像

这样的事情
prog1 | script.pl | prog2

答案 1 :(得分:2)

您不在循环中使用$newc而只打印空白行

foreach $newc (@mass) {
    $counter++;
    if ($newc =~ /^$/) {
        print "blank line found in $old at line number $counter\n";
    } else {
        print $new $newc;
    }
}

如评论中所述,请使用$ARGV[0]$ARGV[1]$ARGV[0]@ARGV的第一个值,而@ARGV[0]是一个切片。有关详细信息,请参阅Slices

答案 2 :(得分:1)

@mass中的行仍包含尾随换行符。要么在正则表达式中考虑,要么限制值。

我会将循环编码为

while (<$old>) {
  chomp;
  say {$new} $_ if length;
}

另外,测试open的返回值:

open my $old, "<", $infile or die qq(Can't open "$infile": $!);

整个代码作为一行代码:

perl -nE'chomp; say if length' infile.txt >outfile.txt

perl -nE'chomp; if(length){say}else{say STDERR "blank on line $."}' infile.txt >outfile.txt

$.是当前的输入行号。)

答案 3 :(得分:-2)

你的脚本应该是这样的:

if (@ARGV != 2) {
  print "Usage: $0 infile outfile\n";
  exit;
}
$infile = $ARGV[0];
$outfile = $ARGV[1];
open $old, "<", $infile;
open $new, ">", $outfile;
@mass = <$old>;
$counter = 0;
foreach $newc (@mass) {
    $counter++;
    if ($newc =~ /^$/) {
        print "blank line found in $infile at line number $counter\n";
    } else { # print in the new file when not an empty line!
        print $new $newc;
    }
}
close($new);
close($old);

答案 4 :(得分:-2)

if (@ARGV != 2) {
  print "Usage: $0 infile outfile\n";
  exit;
}

$infile = $ARGV[0];
$outfile = $ARGV[1];
open(OLD, "<$infile");
open(NEW, ">$outfile");
while ($line = <OLD>) {
    print NEW $line unless ($line =~ /^$/);
}
close(NEW);
close(OLD);