Search code examples
perlsubroutinedereferenceperl-hash

Cannot fire subroutine inside a hash of subroutines in perl


Hi I'm quite new to perl. I have a perl hash containing subroutines. I've tried to run it in various ways that I found online. But nothing seems to work. My code :

%hashfun = (

start=>sub { print 'hello' },
end=>sub { print 'bye' } 

);

And I've tried the following and more.

print "\n $hashfun{start} \n";

which results in the following output:

CODE(< HexaDecimal Value >)

Then I tried

print "\n $hashfun{start}->() \n";

which results in the following

CODE(< HexaDecimal Value >) ->()

How to fix?


Solution

  • Your last attempt ist the right syntax, but in the wrong place. You cannot run code inside of a string interpolation1. Move it outside of the double quotes "".

    print "\n";
    $hashfun{start}->();
    print"\n";
    

    It's important not to print the actual call to $hashfun{start}, because that would return 1. That's because a sub in Perl always returns the return value of the last statement inside the sub (which can be a return). Here, it's a print. And the return value of print is 1 if the printing succeeded. So print "\n", $hashfun{start}->(), "\n"; would output

    hello
    1
    
    

    1) Actually you can, but you really shouldn't.print "\n@{[&{$hashfun{start}}]}\n"; will work. It's very magical and you should really not do that.

    Because arrays can be interpolated into strings, an array deref works inside of double quotes. The stuff inside that deref is being run, so the &$hashfun{start} (which is a different way of calling the coderef) gets run. But because it returns 1 and that's not an array ref, we need to wrap it in [] to put it into an array ref that is then being dereferenced. Please don't use that!