加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 21:48:53 所属栏目:大数据 来源:网络整理
导读:换句话说,我如何检查coderef“相等”? smartmatch操作符不起作用for obvious reasons(将其视为CODE-(ANY)),但我已将其包含在示例中以显示我所追求的内容: use strict;use warnings;use feature 'say';sub pick_at_random { my %table = @_; return ( value
换句话说,我如何检查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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读