无法在perl中的子例程散列中触发子例程

Cannot fire subroutine inside a hash of subroutines in perl

您好,我是 perl 的新手。我有一个包含子例程的 perl 散列。我已经尝试 运行 它以我在网上找到的各种方式。但似乎没有任何效果。 我的代码:

%hashfun = (

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

);

而且我已经尝试了以下以及更多。

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

这导致以下输出:

CODE(< HexaDecimal Value >)

然后我试了

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

结果如下

CODE(< HexaDecimal Value >) ->()

如何修复?

你上次的尝试是正确的语法,但在错误的地方。您不能 运行 在字符串插值 1 内编写代码。将它移到双引号 "".

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

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

hello
1


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

因为数组可以插入到字符串中,所以数组 deref 在双引号内起作用。 deref 中的内容是 运行,因此 &$hashfun{start}(这是调用 coderef 的不同方式)得到 运行。但是因为它 returns 1 而不是数组引用,我们需要将它包装在 [] 中以将其放入数组引用中,然后被取消引用。 请不要使用它!