in reply to reference to self function

if ($self->can($self->{method})) { my $method = $self->{method}; $self->$method(@params); } else { die "Sorry, the method $self->{method} isn't valid!"; }

You might want to restrict access by prefixing a name or a symbol to all methods you want to call this way.

One other tip: the indirect object notation is perilous. I prefer to call constructors with:

my $x = Foo->new(method => 'biscuit');

It's a lot clearer that the method is new, not Foo.

Replies are listed 'Best First'.
Re: Re: reference to self function
by anjiro (Beadle) on Jun 25, 2003 at 07:12 UTC
    I didn't know about "can" - that's pretty neat. But I'd really like to make a reference I can store, since I'll be calling the "method" function throughout the program; what I have in the meantime looks like this:
    sub w { my($self, $a, $i) = @_; if($self->{method} eq 'correlation') { return $self->correlation($a, $i); } if($self->{method} eq 'vector_similarity') { return $self->vector_similarity($a, $i); } if($self->{method} eq 'IUF') { return $self->IUF($a, $i); } if($self->{method} eq 'MSD') { return $self->MSD($a, $i); } }
    The w function gets called quite a few times, so I don't want a per-call check.

    Thanks for the tip on constructors; that's a good point.

    dan