Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Hash of Subfunctions

Tags:

perl

I wish to have a hash containing references to sub-functions where I can call those functions dependent upon a user defined variable, I will try and give a simplified example of what I'm trying to do.

my %colors = (
    vim => setup_vim(),
    emacs => setup_emacs(),
)

$colors{$editor}(arg1, arg2, arg3)

where setup_vim() and setup_emacs() would be sub-functions defined later in my file and $editor is a user defined variable (ie vim or emacs). Is this possible? I can't get it working, or find good information on the subject. Thanks.

(Note I have it implemented right now as a working Switch, but I think a hash like the above would make it easier to add new entries to my existing code)

like image 298
Chris R Avatar asked Feb 04 '11 01:02

Chris R


People also ask

How do I find the hash key in Perl?

Given an expression that specifies an element of a hash, returns true if the specified element in the hash has ever been initialized, even if the corresponding value is undefined. print "Exists\n" if exists $hash{$key}; print "Defined\n" if defined $hash{$key}; print "True\n" if $hash{$key};

How do I undef a hash in Perl?

undef on hash elements The script uses $h{Foo} = undef; to set the value of a hash key to be undef. use strict; use warnings; use Data::Dumper qw(Dumper);

What does @_ mean in Perl?

@ is used for an array. In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function: sub Average{ # Get total number of arguments passed. $ n = scalar(@_); $sum = 0; foreach $item (@_){ # foreach is like for loop...


2 Answers

Here is the syntax.

my %colors = (
    vim => \&setup_vim,
    emacs => \&setup_emacs,
);

$colors{$editor}(@args)

Note that you can actually create functions directly with

my %colors = (
    vim => sub {...},
    emacs => sub {...},
);

And if you're familiar with closures, Perl supports full closures for variables that have been declared lexically, which you can do with my.

like image 114
btilly Avatar answered Sep 19 '22 17:09

btilly


You have to pass a reference to the subroutine you want to call into the hash.

Here's an example:

sub myFunc {
   print join(' - ', @_);
}

my %hash = ( key => \&myFunc );
$hash{key}->(1,2,3);

With \&myFunc you get the reference wich points at the function. Important is to leave the () away. Ohterwise you would pass through a reference to the return value of the function.

When calling the function by reference you have to derefence it with the -> operator.

like image 23
Sven Eppler Avatar answered Sep 19 '22 17:09

Sven Eppler