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

前端之家收集整理的这篇文章主要介绍了如何检查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

原文链接:https://www.f2er.com/Perl/172255.html

猜你在找的Perl相关文章