换句话说,我如何检查coderef“相等”?
smartmatch操作符不起作用for obvious reasons(将其视为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
开始:
Using a reference as a number produces an integer representing its storage location in memory. The only useful thing to be done with this is to compare two
references numerically to see whether they refer to the same location.06001