我正在用Perl编写脚本,在这个脚本中,我必须在代码中打开同一文件两次。这是我对代码的概述:
#!/usr/bin/perl
use strict;
use warnings;
my %forward=();
my %reverse=();
while(<>){
chomp;
# store something
}
}
while(<>){ # open the same file again
chomp;
#print something
}
我使用菱形运算符,所以我像这样运行脚本
perl script.pl input.txt
但这不会产生任何输出。如果我使用filehandle打开文件,脚本就会工作。这里会有什么问题呢?
发布于 2017-08-03 15:57:53
在耗尽@ARGV
之前保存它。当然,这只适用于在命令行中指定的实际文件,而不适用于STDIN
。
#!/usr/bin/env perl
use strict;
use warnings;
run(@ARGV);
sub run {
my @argv = @_;
first(@argv);
second(@argv);
}
sub first {
local @ARGV = @_;
print "First pass: $_" while <>;
}
sub second {
local @ARGV = @_;
print "Second pass: $_" while <>;
}
发布于 2017-08-03 16:53:33
您在第一个循环中读取了所有要读取的内容,而在第二个循环中没有留下任何要读取的内容。
如果输入不是很大,您可以简单地将其加载到内存中。
my @lines = <>;
chomp( @lines );
for (@lines) {
...
}
for (@lines) {
...
}
https://stackoverflow.com/questions/45489150
复制