perl - "tee"qx运算符

asc*_*ler 3 perl redirect

我正在编写一个目前有以下脚本的脚本:

my @files = `$some_command`;
print @files;
chomp @files;
foreach my $file (@files)
{
    process($file);
}
Run Code Online (Sandbox Code Playgroud)

它工作正常,但该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>; }
Run Code Online (Sandbox Code Playgroud)

但是如果有一个更简单的解决方案,我宁愿避免使用临时文件.

Col*_*ell 5

您可以打开手柄并在打印线条时自己手动填充阵列.

像这样的东西可能会起作用,

  open my $fh, '-|', $some_command;
  while(<$fh>)
  {
    print $_;
    push @files, $_;
  }
  close $fh;
Run Code Online (Sandbox Code Playgroud)