2014-02-07 21 views
2

我有一個文件句柄,其中包含$ 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並行--compress。

回答

1

有沒有必要打破STDIN。使用IPC::Open2IPC::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如果你是從外部程序感興趣的標準錯誤流中)