aoiee
aoiee

Reputation: 355

Perl - capturing undefined keys in a class?

We can capture undefined methods using AUTOLOAD, is there a way to capture undefined variables in a class instance?

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

Upvotes: 0

Views: 39

Answers (1)

mob
mob

Reputation: 118605

Your class can wrap a 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};

Output:

fieldname is undefined! at 45357987.pl line 10.

Upvotes: 1

Related Questions