使用 autodie,你不需要检查文件 openclose 失败

autodie 允许你使用文件而无需显式检查打开/关闭失败

从 Perl 5.10.1 开始, autodie pragma 已经在核心 Perl 中可用。使用时,Perl 会在打开和关闭文件时自动检查错误。

下面是一个示例,其中读取一个文件的所有行,然后将其写入日志文件的末尾。

use 5.010;    # 5.010 and later enable "say", which prints arguments, then a newline
use strict;   # require declaring variables (avoid silent errors due to typos)
use warnings; # enable helpful syntax-related warnings
use open qw( :encoding(UTF-8) :std ); # Make UTF-8 default encoding
use autodie;  # Automatically handle errors in opening and closing files

open(my $fh_in, '<', "input.txt"); # check for failure is automatic

# open a file for appending (i.e. using ">>")
open( my $fh_log, '>>', "output.log"); # check for failure is automatic

while (my $line = readline $fh_in) # also works: while (my $line = <$fh_in>)
{
     # remove newline
     chomp $line;

     # write to log file
     say $fh_log $line or die "failed to print '$line'"; # autodie doesn't check print
}

# Close the file handles (check for failure is automatic)
close $fh_in;
close $fh_log;

顺便说一句,你应该在技术上总是检查 print 语句。许多人没有,但是 perl(Perl 解释器)不会自动执行此操作,也不会执行此操作