Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Problems calling subroutines by reference using a hash value


In Perl, you are able to call a function by reference (or name) like so:

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

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

What I am trying to do is use a value from a Hash, like so:

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

    &$hash{functionName}();

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

And the error I get is Global symbol "$hash" requires explicit package name.

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

like image 702
Thumper Avatar asked Jun 20 '12 16:06

Thumper


1 Answers

It's just a precedence issue that can be resolved by not omitting the curlies. You could use

&{ $hash{functionName} }()

Or use the alternate syntax:

$hash{functionName}->()

As between indexes, the -> can be omitted (but I don't omit it here):

$hash{functionName}()

Ref: Deferencing Syntax

like image 62
ikegami Avatar answered Sep 19 '22 23:09

ikegami