微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何检查Perl标量是否包含对某个子例程的引用?

换句话说,我如何检查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

Live in action here

当引用被赋予重载==或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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐