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)
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};
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);
@ 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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With