我喜欢使用IO::File
打开和读取文件,而不是内置方式。
内置方式
open my $fh, "<", $flle or die;
IO :: File
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
? 最佳答案
您可以像在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功能的其余部分,那么谁在乎初始化程序的外观呢?关于perl - 不读取实际文件时使用`IO::Handle`或`IO::File`的Perl,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21465584/