Orsmo has asked for the wisdom of the Perl Monks concerning the following question:
In the module that defines the subclass, Some/Package/Sub.pm, I have the following:package Some::Package; use strict; use warnings; our $VERSION = '0.1'; our $AUTOLOAD; my %fields = ( name => undef, ); sub new { my $proto = shift; my $class = ref($proto) || $proto; my %args = @_; my $self = { _permitted => \%fields, %fields, }; bless($self, $class); foreach my $arg (keys(%args)) { $self->$arg($args{$arg}); } sub AUTOLOAD { my $self = shift; my $type = ref($self) or croak "$self is not an object"; my $name = $AUTOLOAD; $name =~ s/.*://; unless(exists $self->{_permitted}->{$name} ) { croak "Can't access `$name' field in class $type"; } if (@_) { return $self->{$name} = shift; } else { return $self->{$name}; } } 1;
Finally, my test script looks something like this:package Some::Package::Sub; use strict; use warnings; our $VERSION = '0.1'; our $AUTOLOAD; my %fields = ( name => undef, needthis => undef, ); 1;
Now, it seems that Some::Package::Sub inherits the constructor and AUTOLOAD methds just fine, but that the inherited constructor, which makes use of a reference to the file scoped lexical %fields, refers to the hash in Some/Package.pm even though I'm calling Some::Package::Sub->new(). This means that the data accessor for the needthis attribute is not available in Some::Package::Sub objects. How do I solve this?use strict; use warnings; use Some::Package; use Some::Package::Sub; my $object = Some::Package::Sub->new( name => 'Test', needthis => 'Value', }
|
|---|