我正在编写一个脚本,目前有:
my @files = `$some_command`;
print @files;
chomp @files;
foreach my $file (@files)
{
process($file);
}
它工作正常,但 some_command
部分占用了脚本的大部分时间。在那段时间里,stdout 上什么也没有出现,因为 Perl 已经重定向了 some_command
的输出来填充 @files
数组。只有在 some_command
完成并且 Perl 继续执行 print @files;
时才会打印它。
是否有一些巧妙的方法可以更改此代码,以便 some_command
的输出在执行时出现?我也许可以使用 tee(1)
尝试这样的事情:
my $tmpfile = File::Temp->new();
system("$some_command | tee " . $tmpfile->filename);
my @files;
{ local $/ = undef; @files = split /\s/, <$tmpfile>; }
但如果有更简单的解决方案,我宁愿避免使用临时文件。
最佳答案
您可以在打印行的同时自己打开句柄并手动填充数组。
这样的事情可能会奏效,
open my $fh, '-|', $some_command;
while(<$fh>)
{
print $_;
push @files, $_;
}
close $fh;
关于perl - "tee"qx 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5032352/