我喜欢使用 IO::File
打开和读取文件,而不是内置的方式。
内置方式
open my $fh, "<", $flle or die;
IO::文件
use IO::File;
my $fh = IO::File->new( $file, "r" );
但是,如果我将命令的输出视为我的文件呢?
内置的 open
函数允许我这样做:
open my $cmd_fh, "-|", "zcat $file.gz" or die;
while ( my $line < $cmd_fh > ) {
chomp $line;
}
IO::File
或 IO::Handle
的等价物是什么?
顺便说一下,我知道可以这样做:
open my $cmd_fh, "-|", "zcat $file.gz" or die;
my $cmd_obj = IO::File-> new_from_fd( fileno( $cmd_fh ), 'r' );
但是如果已经有一个文件句柄,为什么还要使用 IO::File
呢?
最佳答案
首先,如果 $file
包含空格或其他特殊字符,您的代码片段将失败。
open my $cmd_fh, "-|", "zcat $file.gz" or die $!;
应该是
open my $cmd_fh, "-|", "zcat", "$file.gz" or die $!;
或
use String::ShellQuote qw( shell_quote );
open my $cmd_fh, "-|", shell_quote("zcat", "$file.gz") or die $!;
或
use String::ShellQuote qw( shell_quote );
open my $cmd_fh, shell_quote("zcat", "$file.gz")."|" or die $!;
我提到后一种变体,因为将单个 arg 传递给 IO::File->open
归结为将该 arg 传递给 open($fh, $that_arg)
, 所以你可以使用
use String::ShellQuote qw( shell_quote );
IO::File->open(shell_quote("zcat", "$file.gz")."|") or die $!;
如果您只想使用 IO::File 的方法,则不需要使用 IO::File->open
。
use IO::Handle qw( ); # Needed on older versions of Perl
open my $cmd_fh, "-|", "zcat", "$file.gz" or die $!;
$cmd_fh->autoflush(1); # Example.
$cmd_fh->print("foo"); # Example.
关于Perl 在不读取实际文件时使用 `IO::Handle` 或 `IO::File`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21465584/