Perl: problems calling subroutines by reference using a hash value


In Perl, you can call a function by reference (or name) as follows:

    my $functionName = 'someFunction';
    &$functionName();

    #someFunction defined here:
    sub someFunction { print "Hello World!"; }

What I'm trying to do is use a value from Hash, for example:

    my %hash = (
        functionName => 'someFunction',
    );

    &$hash{functionName}();

    #someFunction defined here:
    sub someFunction { print "Hello World!"; }

And the error I get is that the global character "$ hash" requires an explicit package name.

My question is: is there a proper way to do this without using an intermediate variable?
Any help on this would be greatly appreciated!

+5
source share
1 answer

This is simply a priority problem that can be solved without lowering the knees. you can use

&{ $hash{functionName} }()

Or use alternative syntax:

$hash{functionName}->()

-> ( ):

$hash{functionName}()

:

+12

All Articles