我们可以使用AUTOLOAD
捕获未定义的方法,有没有办法在类实例中捕获未定义的变量?
package Example;
sub new {
my ($class) = @_;
my $self = {};
bless($self, $class);
return $self;
}
sub AUTOLOAD {
print("hello\n");
}
use Example;
my $exp = Example->new();
$exp->methodname; # prints "hello"
$exp->{fieldname}; # currently undefined
答案 0 :(得分:1)
您的课程可以打包tied hash
package Example::Tie;
sub TIEHASH {
my ($pkg,@list) = @_;
bless { @list }, $pkg;
}
sub FETCH {
my ($tied,$key) = @_;
if (!defined($tied->{$key})) {
warn "$key is undefined!";
}
$tied->{$key};
}
sub STORE {
my ($tied,$key,$val) = @_;
$tied->{$key} = $val;
}
package Example;
sub new {
my ($pkg,@list) = @_;
my $self = {};
tie %$self, 'Example::Tie', @list;
bless $self, $pkg;
}
###########
package main;
my $exp = Example->new();
print $exp->{fieldname};
输出:
fieldname is undefined! at 45357987.pl line 10.