当然,codaddict的答案是正确的,但我想补充一些言论:
use strict;
use warnings;
:
你应该总是与这两条线开始你的脚本
使用三个参数开放和测试错误:
open my $fh, '<', $file or die "unable to open '$file' for reading : $!";
而且由于use strict
你必须声明所有变量。所以,你的脚本将是这样的:
#!/usr/bin/perl
use strict;
use warnings;
my $pattern = $ARGV[0];
my $file = $ARGV[1];
open $fh, '<', $file or die "unable to open file '$file' for reading : $!";
my @arr = <$fh>;
close $fh; # close as soon as possible
my @lines = grep /$pattern/, @arr;
print @lines;
如果文件很大,你可以完全避免在内存中读取数据:
#!/usr/bin/perl
use strict;
use warnings;
my $pattern = qr/$ARGV[0]/;
my $file= $ARGV[1];
print "pattern=$pattern\n";
my @lines;
open my $fh, '<', $file or die "unable to open file '$file' for reading : $!";
while(my $line=<$fh>) {
push @lines, $line if ($line =~ $pattern);
}
close($fh);
print @lines;
- 谢谢明白了。 – TCM 2010-10-03 03:23:40
@coddadict,你做了很大的修复代码中的错误,但这个问题和用户使用的方法将它转换成准'xy问题',所以这是灌输可能不是主题的情况之一。我会建议不要同时阅读整个文件(他希望模拟面向行的grep),我会用grep {}而不是grep()来推荐他,以创建一个好习惯,而三个争论开放。甚至进一步向他展示在线方法(或者逐行的方式)将会是一个加分。 – 2010-10-03 17:11:03