Hash of functions in modules

V

Vito Corleone

Hi,

I have code like this:

if ($cmd eq "get") { $self->get(); }
elsif ($cmd eq "set") { $self->set(); }
elsif ($cmd eq "copy") { $self->copy(); }

I want to put it inside hash of function. How do I do that? I know I can
do:

%hof = ( get => \&get,
set => \&set,
copy => \&copy );
$hof{$cmd}->();

But I will lose the $self in the function. How do I pass $self to the
function too as well?
 
A

Ala Qumsieh

Vito said:
if ($cmd eq "get") { $self->get(); }
elsif ($cmd eq "set") { $self->set(); }
elsif ($cmd eq "copy") { $self->copy(); }

Perl allows this:

$self->$cmd;

--Ala
 
T

Tassilo v. Parseval

Also sprach Ala Qumsieh:
Perl allows this:

$self->$cmd;

And in case $cmd can contain garbage (that is, the name of a
non-existing method), one could catch that with an autoloader:

our $AUTOLOAD;
...

sub DESTROY { }
sub AUTOLOAD {
die "No such method: $AUTOLOAD";
}

Tassilo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top