Zubinix has asked for the wisdom of the Perl Monks concerning the following question:

Hi

If I have a function reference declared in a hash such as:

(
"my_function" => \&my_func
)

How do I call this function with an argument? When I do:

my $func_ref = %hash{"my_function"};
&$func_ref($arg1);

I get a "Can't use string ("1") as a HASH ref..." error. What am I doing wrong?
Thanks!
  • Comment on Calling a function reference with arguments

Replies are listed 'Best First'.
Re: Calling a function reference with arguments
by Joost (Canon) on Apr 17, 2007 at 23:37 UTC
Re: Calling a function reference with arguments
by GrandFather (Saint) on Apr 17, 2007 at 23:42 UTC

    I strongly advise you use strictures (use strict; use warnings;) which would have told you about the syntax error in my $func_ref = %hash{"my_function"};. Using & to call a sub is somewhat out of favor. The following may get you sorted out:

    use strict; use warnings; my %hash = (hello => "Hello World\n", my_function => \&my_func); my $funcref = $hash{my_function}; &$funcref (\%hash); $funcref->(\%hash); sub my_func { my $hashref = shift; print $hashref->{hello} }

    Prints:

    Hello World Hello World

    DWIM is Perl's answer to Gödel
Re: Calling a function reference with arguments
by Zubinix (Acolyte) on Apr 17, 2007 at 23:40 UTC
    I think I've fixed my problem, I was not dereferencing a hash as I thought in the line:

    my $func_ref=%hash{"my_function"};

    Once I fixed that, things seem to work.

    Funny error message though, how would you interpret this error message?
        Yep, it should have been $hash{"my_function"}.

      I get:

      syntax error at noname.pl line 2, near "%hash{" Execution of noname.pl aborted due to compilation errors.

      with:

      my %hash = (hello => "Hello World\n", my_function => \&my_func); my $func_ref = %hash{"my_function"}; $func_ref-> (\%hash); sub my_func { my $hashref = shift; print $hashref->{hello} }

      so it seems the sample code you provided is not quite the same as the code you tested, or there is a Perl version difference issue perhaps? (I'm using AS Perl v5.8.7)


      DWIM is Perl's answer to Gödel