作者:Defect___219 | 来源:互联网 | 2022-11-02 17:08
几种unix实用程序,例如fmt,head和cat,可以通过以下三种方式中的任何一种来接收数据:来自标准输入的管道;或重定向“ <”。例如:
printf '%b' 'dog \ncat \nrat\n' > dogcatrat
fmt dogcatrat
cat dogcatrat | fmt
fmt
可以编写一种功能相同的perl脚本吗?还是有充分的理由不尝试这样做?“标准输入的管道”是引用以cat开头的代码行的正确方法吗?
我想编写myfmt.pl,以这三种方式中的任何一种使用。
1> Grinnz..:
ARGV
默认情况下,特殊文件句柄将执行此操作。当没有给定句柄时,它也是readline使用的句柄(又名<>
and <<>>
操作符)。因此,这实际上在Perl脚本中很常见。
#!/usr/bin/env perl
use 5.022;
use warnings;
while (my $line = <<>>) {
# $line from one of the filenames passed as an argument, otherwise STDIN
# $ARGV is the current filename, or - when reading from STDIN
}
您可以改用<>
运算符来支持较早版本的Perl,但如果可用,Perl 5.22中添加的<<>>
运算符是更好的选择,因为标准运算符允许传递诸如运行进程之类的奇怪信息,而不是读取文件。<>
date|
为了在支持较旧版本的Perl时更安全的仅文件名操作,您可以使用ARGV :: readonly或模拟如下<<>>
操作符:
#!/usr/bin/env perl
use strict;
use warnings;
unshift @ARGV, '-' unless @ARGV;
while (my $file = shift) {
my $fh;
if ($file eq '-') {
$fh = \*STDIN;
} else {
open $fh, '<', $file or die "open $file failed: $!";
}
while (my $line = <$fh>) {
# ...
}
}
(从技术上讲,<<>>
操作员也不允许将其-
作为参数传递来读取STDIN,但如果要允许这样做,则由您选择。)