[英]Why can I print this treating as a reference and treating it as a scalar?
[英]why reference of a function is being returned as SCALAR
我无法理解,如果我取消注释返回行,那么输出将是“CODE”,否则“SCALAR”..为什么会这样?
use strict;
sub test {
my ($abc,$grab) = @_;
print 'i m here';
print $abc;
## return []; if uncommented then output will be "REF" else "SCALAR"
}
my $pass= "i m good";
my %my_hash = ();
$my_hash{'fun'} = \&test($pass);
print ref($my_hash{'fun'})
您没有参考函数。
当你写:
\&test($pass);
这是一个函数调用(你有一个参数列表)。
因此,使用参数$pass
调用函数test
,然后引用返回的值(除非您知道并且特别需要它做什么,否则不应该使用&
前缀函数调用)。
如果您想要参考test
,您应该使用
$my_hash{'fun'} = \&test; ### (1)
如果要引用一个函数,该函数使用当前范围内的参数$pass
调用test
,则应使用:
$my_hash{'fun'} = sub { test($pass) }; ### (2)
请注意,后者将在当前范围内的变量$pass
创建一个闭包。 要调用(1),您可以使用$my_hash{fun}->($some_arg)
。 要调用(2),使用$my_hash{fun}->()
。
如果没有隐式return
,子例程将返回最后一个表达式的值。 print
在成功时返回1,即标量。
\\&test($pass)
与\\ test($pass)
,即它计算为对子test
返回的值的引用。 如果它从print
返回1,你将获得SCALAR,如果它返回[]
,你将得到REF,因为你有一个对数组的引用的引用。 您也可以通过解除引用来验证它:
print ${ $my_hash{fun} }, ': ', ref $my_hash{fun}, "\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.