If I have a Perl class eg
package Foo;
sub new {
my ($class,$hashref) = @_;
my $self = bless $hashref, $class;
}
and initialised with
my $foo = Foo->new( { bar => 2, othervar => 8 } );
I can do
print $foo->{ bar };
which feels clunky, and
print $foo->bar
feels more preferable. However, if there are a lot of keys, I'd prefer not to have to write an accessor for every key (or is that best practice) ?
So, I can include
our $AUTOLOAD;
sub AUTOLOAD {
my $self = shift;
my $called = $AUTOLOAD =~ s/.*:://r;
die "No such attribute: $called"
unless exists $self->{$called};
return $self->{$called};
}
sub DESTROY { } # see below
In perldoc perlobj it says
# XXX - this is a terrible way to implement accessors
Are there any good ways to implement accessors like this, without using other packages, eg Moose, Class::Accessor ? I'm just after something light as its just one class that has a lot of keys.