我有一个文件句柄,其中包含$ my_fd中的压缩数据。我想启动一个解压缩程序(例如“lzop -dc”),将$ my_fd重定向为标准输入,这样我就可以读取$ out_fd中的解压缩输出。当我在其他地方使用STDIN时,这段代码不起作用(但它显示了这个想法):
# Save STDIN file handle
open(my $stdin_copy, "<&", "STDIN");
my $fd = $my_fd;
# Replace STDIN with the file handle
open(STDIN, "<&", $fd);
# Start decompression with the fake STDIN
open($out_fd, "-|", $opt::decompress_program);
# Put STDIN file handle back
open(STDIN, "<&", $stdin_copy);
# Do stuff on the decompressed data
while(<$out_fd>) { ... }
# Do more stuff on the original STDIN
输入($ fd)和输出($ out_fd)都可能比物理内存大,所以不能全部读取它。
背景
这将用于GNU Parallel中的--compress。
答案 0 :(得分:1)
没有必要破坏你的STDIN
。使用IPC::Open2
或IPC::Run
来使用具有任意输入/输出流的外部程序。
use IPC::Open2;
# use $fd as input and $out_fd as output to external program
$pid = open2($fd, $out_fd, $opt::decompress_program);
close $fd;
while (<$out_fd>) {
...
}
(如果您对来自外部程序的标准错误流感兴趣,请使用IPC::Open3
)