我正在编写一个脚本,该脚本当前包含:
my @files = `$some_command`;
print @files;
chomp @files;
foreach my $file (@files)
{
process($file);
}它可以正常工作,但some_command部分占用了脚本的大部分时间。在此期间,标准输出上没有任何内容,因为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>; }但如果有更简单的解决方案,我宁愿避免临时文件的东西。
发布于 2011-02-18 01:37:57
您可以打开句柄并在打印行时自己手动填充数组。
像这样的东西也许能行得通,
open my $fh, '-|', $some_command;
while(<$fh>)
{
print $_;
push @files, $_;
}
close $fh;发布于 2011-02-18 01:39:44
您可以跳过qx()操作符,直接打开进程输出流的文件句柄。此代码在功能上等同于my @files = qx($some_command)
my @files = ();
open my $proc_fh, "$some_command |";
while (<$proc_fh>) {
push @files, $_;
}
close $proc_fh;但是在while循环中,您可以使用$_做任何您想做的事情
while (<$proc_fh>) {
print "INPUT: $_\n";
push @files, $_;
}一个重要的考虑因素是$some_command的输出缓冲行为。如果该命令缓冲了其输出,那么$proc_fh处理程序将不会接收任何输入,直到有大量数据可用为止。
发布于 2011-02-18 01:33:20
File::Tee模块看起来可以做您想做的事情。这里有一些在运行system()时重定向STDOUT的例子。我还没有用过它,所以我不能给出更多具体的例子,但看起来这将是一个很好的起点。
https://stackoverflow.com/questions/5032352
复制相似问题