1

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?

4

1 回答 1

7

您的最后一次尝试是正确的语法,但在错误的位置。您不能在字符串插值1内运行代码。将它移到双引号之外""

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

重要的是不要print实际调用$hashfun{start},因为那会返回1。这是因为 Perl 中的 sub 总是返回 sub 中最后一条语句的返回值(可以是 a return)。在这里,它是一个print. 的返回值print1打印是否成功。所以print "\n", $hashfun{start}->(), "\n";会输出

你好
1


1)实际上你可以,但你真的不应该。print "\n@{[&{$hashfun{start}}]}\n";将工作。这是非常神奇的,你真的不应该那样做。

因为数组可以插入到字符串中,所以数组 deref 在双引号内起作用。该 deref 中的东西正在运行,因此&$hashfun{start}(这是调用 coderef 的另一种方式)运行。但是因为它返回1并且它不是一个数组 ref,所以我们需要将它包装[]到一个数组 ref 中,然后再取消引用。请不要使用那个!

于 2016-11-23T10:48:46.203 回答