我喜欢使用IO::File打开和读取文件而不是内置方式.
open my $fh, "<", $flle or die;
Run Code Online (Sandbox Code Playgroud)
use IO::File;
my $fh = IO::File->new( $file, "r" );
Run Code Online (Sandbox Code Playgroud)
但是,如果我将命令的输出视为我的文件怎么办?
内置open函数允许我这样做:
open my $cmd_fh, "-|", "zcat $file.gz" or die;
while ( my $line < $cmd_fh > ) {
chomp $line;
}
Run Code Online (Sandbox Code Playgroud)
什么相当于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' );
Run Code Online (Sandbox Code Playgroud)
但是,IO::File如果已经存在文件句柄,为什么还要费心呢?
首先,如果$file包含空格或其他特殊字符,则代码段会失败.
open my $cmd_fh, "-|", "zcat $file.gz" or die $!;
Run Code Online (Sandbox Code Playgroud)
应该
open my $cmd_fh, "-|", "zcat", "$file.gz" or die $!;
Run Code Online (Sandbox Code Playgroud)
要么
use String::ShellQuote qw( shell_quote );
open my $cmd_fh, "-|", shell_quote("zcat", "$file.gz") or die $!;
Run Code Online (Sandbox Code Playgroud)
要么
use String::ShellQuote qw( shell_quote );
open my $cmd_fh, shell_quote("zcat", "$file.gz")."|" or die $!;
Run Code Online (Sandbox Code Playgroud)
我提到了后面的变种,因为将一个arg传递给IO::File->openboig传递给arg open($fh, $that_arg),所以你可以使用
use String::ShellQuote qw( shell_quote );
IO::File->open(shell_quote("zcat", "$file.gz")."|") or die $!;
Run Code Online (Sandbox Code Playgroud)
如果您只想使用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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
825 次 |
| 最近记录: |