in reply to Link methods to hash values

Why not simply provide a 'get' method?

$self->get ('name'); ... sub get { my ($self, $param) = @_; return undef if ! exists $self->{$param}; return $self->{$param}; }

Alternatively there are CPAN modules such as Class::MethodMaker that will generate getters and setters for you given a list of properties.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Link methods to hash values
by chromatic (Archbishop) on Oct 01, 2006 at 23:30 UTC
       return undef if ! exists $self->{$param};

    That's more correct (and, in my opinion, readable) as:

       return unless exists $self->{$param};

    Beware of undef in list context.

Re^2: Link methods to hash values
by Herkum (Parson) on Oct 01, 2006 at 19:08 UTC

    I just wanted to use a more explicit method name rather than pass a value all the time. I figured it, cannot be that hard right?

    Let me take a look at Class:MethodMaker and see if that gives me what I want...

    Thanks!

      If you don't want to use something like Class::MethodMaker, it's pretty trivial to do this sort of thing yourself.

      package Foo; use strict; use warnings; foreach my $name(qw(foo bar baz quux narf)) { no strict 'refs'; *{ 'Foo::get_' . $name } = sub { my $self = shift; return $self->{$name}; }; }

      Constructing the equivelent set_* methods is left as an exercise for the reader. :)

        This looks much easier and cleaner to implement. I am going to put this and see how much I break! :)