[英]How can I check if a Perl scalar holds a reference to a certain subroutine?
换句话说,我如何检查coderef“相等”?
smartmatch运算符由于显而易见的原因而无法工作(将其视为CODE->(ANY)
),但我已将其包含在示例中以显示我所追求的内容:
use strict;
use warnings;
use feature 'say';
sub pick_at_random {
my %table = @_;
return ( values %table )[ rand( keys %table ) ];
}
my %lookup = ( A => \&foo,
B => \&bar,
C => \&baz );
my $selected = pick_at_random( %lookup );
say $selected ~~ \&foo ? "Got 'foo'" :
$selected ~~ \&bar ? "Got 'bar'" :
$selected ~~ \&baz ? "Got 'baz'" :
"Got nadda" ;
您可以使用普通(数字)相等( ==
),就像所有引用的情况一样:
Perl> $selected == \&foo
Perl> $selected == \&bar
Perl> $selected == \&baz
1
当引用被赋予重载==
或0+
东西(这对于coderefs来说不太可能)时,它会中断。 在这种情况下,您将比较Scalar::Util::refaddr($selected)
。
来自man perlref
:
使用引用作为数字会生成一个整数,表示其在内存中的存储位置。 要做的唯一有用的事情是用数字比较两个引用,看它们是否引用相同的位置。
if ($ref1 == $ref2) { # cheap numeric compare of references print "refs 1 and 2 refer to the same thing\\n"; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.