Perl在不读取实际文件时使用`IO :: Handle`或`IO :: File`

时间:2014-01-30 19:19:56

标签: perl file-io

我喜欢使用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::FileIO::Handle

顺便说一句,我知道可以这样做:

open my $cmd_fh,  "-|", "zcat $file.gz" or die;
my $cmd_obj = IO::File-> new_from_fd( fileno( $cmd_fh ), 'r' );

但是,如果已有文件句柄,为什么还要费心IO::File

3 个答案:

答案 0 :(得分:5)

首先,如果$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.

答案 1 :(得分:1)

您可以像在open中一样打开它们,因为这正是IO::File所做的 - 它初始化IO::Handle对象并将其链接到使用Perl的本机open打开的文件。

use IO::File;

if (my $fh = new IO::File('dmesg|')) {
   print <$fh>;
   $fh->close;
}

IO::File实际上只是一个非常好的包装器。如果它对你来说不够复杂,你可以从任何你喜欢的FD开始IO::Handle。我想,你需要其余的IO :: * OO功能,那么谁在乎初始化程序是什么样的?

答案 2 :(得分:0)

如果您想使用IO::Handle的管道,可以使用IO::Pipe模块。