我试图理解为什么IO::File似乎不适用use autodie:
示例#1:测试程序使用open:
#! /usr/bin/env perl
#
use strict;
use warnings;
use feature qw(say);
use autodie;
use IO::File;
open( my $fh, "<", "bogus_file" );
# my $fh = IO::File->new( "bogus_file", "r" );
while ( my $line = $fh->getline ) {
chomp $line;
say qq(Line = "$line");
}
Run Code Online (Sandbox Code Playgroud)
这失败了:
Can't open 'bogus_file' for reading: 'No such file or directory' at ./test.pl line 9
Run Code Online (Sandbox Code Playgroud)
它看起来像是autodie在工作.
示例#2:相同的测试程序,但现在使用IO::File:
#! /usr/bin/env perl
#
use strict;
use warnings;
use feature qw(say);
use autodie;
use IO::File;
# open( my $fh, "<", "bogus_file" );
my $fh = IO::File->new( "bogus_file", "r" );
while ( my $line = $fh->getline ) {
chomp $line;
say qq(Line = "$line");
}
Run Code Online (Sandbox Code Playgroud)
这失败了:
Can't call method "getline" on an undefined value at ./test.pl line 11.
Run Code Online (Sandbox Code Playgroud)
看起来autodie没有抓到糟糕的IO::File->new开放.
然而,就我所知,在下面IO::File->new使用open.这是以下代码IO::File:
sub new {
my $type = shift;
my $class = ref($type) || $type || "IO::File";
@_ >= 0 && @_ <= 3
or croak "usage: $class->new([FILENAME [,MODE [,PERMS]]])";
my $fh = $class->SUPER::new();
if (@_) {
$fh->open(@_) # <-- Calls "open" method to open file.
or return undef;
}
$fh;
}
sub open {
@_ >= 2 && @_ <= 4 or croak 'usage: $fh->open(FILENAME [,MODE [,PERMS]])';
my ($fh, $file) = @_;
if (@_ > 2) {
my ($mode, $perms) = @_[2, 3];
if ($mode =~ /^\d+$/) {
defined $perms or $perms = 0666;
return sysopen($fh, $file, $mode, $perms);
} elsif ($mode =~ /:/) {
return open($fh, $mode, $file) if @_ == 3;
croak 'usage: $fh->open(FILENAME, IOLAYERS)';
} else {
# <--- Just a standard "open" statement...
return open($fh, IO::Handle::_open_mode_string($mode), $file);
}
}
open($fh, $file);
}
Run Code Online (Sandbox Code Playgroud)
导致autodie不能按预期工作的原因是什么?