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

标签 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 呢?

最佳答案

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

相关文章:

c - 写入文件时出现 "Permission denied"错误,但前提是该文件尚不存在

java - 写入字节数组时出现 IOException

Perl `use qw` 或从 pm 文件导入子程序

windows - 我是否需要 PATH 中的 Perl bin 目录来运行 perl 程序(在 Windows 上)?

c# - 如何将不同类型的数据存储在一个文件中?

c - 使用 Execl 执行我的程序

android - 如何在 Android 设备的根目录中创建/写入文件?

perl - 一次处理一封邮件

Perl CGI 可靠地读取 url_param 和 param

Perl: `die` 在使用 gzip 打开不存在的 gz 文件时不起作用