我试图理解为什么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");
}
这失败了:
Can't open 'bogus_file' for reading: 'No such file or directory' at ./test.pl line 9
看起来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");
}
这失败了:
Can't call method "getline" on an undefined value at ./test.pl line 11.
看起来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);
}
导致autodie
无法正常工作的原因是什么?
答案 0 :(得分:5)
autodie
是词法范围的。因此,它会在您的文件中更改(换行)open
,但不会在IO::File
内。