钻石运算符 <> 表示:
查看@ARGV 中的名称并将它们视为您要打开的文件。
只需遍历所有这些,就好像它们是一个大文件一样。
实际上,Perl 为此目的使用 ARGV 文件句柄
如果没有给出命令行参数,请改用STDIN。
所以如果一个文件不存在,Perl 会给你一个错误消息 (Can't open nonexistant_file: ...) 并继续处理下一个文件。这是你通常想要的。如果不是这种情况,请手动执行。盗自perlop page:
unshift(@ARGV, '-') unless @ARGV;
FILE: while ($ARGV = shift) {
open(ARGV, $ARGV);
LINE: while (<ARGV>) {
... # code for each line
}
}
遇到问题时,open function 返回一个错误值。所以总是调用openlike
open my $filehandle "<", $filename or die "Can't open $filename: $!";
$! 包含失败的原因。除了dieing,我们还可以做一些其他的错误恢复:
use feature qw(say);
@ARGV or @ARGV = "-"; # the - symbolizes STDIN
FILE: while (my $filename = shift @ARGV) {
my $filehandle;
unless (open $filehandle, "<", $filename) {
say qq(Oh dear, I can't open "$filename". What do you wan't me to do?);
my $tries = 5;
do {
say qq(Type "q" to quit, or "n" for the next file);
my $response = <STDIN>;
exit if $response =~ /^q/i;
next FILE if $response =~ /^n/i;
say "I have no idea what that meant.";
} while --$tries;
say "I give up" and exit!!1;
}
LINE: while (my $line = <$filehandle>) {
# do something with $line
}
}