Perl Hash of Subfunctions
I wish to have a hash containing references to sub-functions where I can call those functions dependent upon a user def开发者_运维技巧ined 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)
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.
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.
精彩评论