Perl Hash Subfunctions

I want to have a hash containing references to subfunctions where I can call these functions depending on a user variable, I will try to give a simplified example of what I am trying to do.

my %colors = ( vim => setup_vim(), emacs => setup_emacs(), ) $colors{$editor}(arg1, arg2, arg3) 

where setup_vim() and setup_emacs() will be the subfunctions defined later in my file, and $editor is a user-defined variable (i.e. vim or emacs). Is it possible? I cannot get it to work or find good information on this. Thanks.

(Note that I implemented this now as a working switch, but I think a hash like the one above will make it easier to add new entries to my existing code)

+7
source share
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 using

 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 mine.

+16
source

You need to pass the link to the routine that you want to call the hash.

Here is an example:

 sub myFunc { print join(' - ', @_); } my %hash = ( key => \&myFunc ); $hash{key}->(1,2,3); 

With \ & myFunc you get a link in which the functions are indicated. It is important to leave () off. Otherwise, you will pass a link to the return value of the function.

When calling a function by reference, you need to eliminate it using the → operator.

+3
source

All Articles