gpt4 book ai didi

perl - 如何检查 Perl 标量是否拥有对某个子例程的引用?

转载 作者:行者123 更新时间:2023-12-03 00:01:01 26 4
gpt4 key购买 nike

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

      if ($ref1 == $ref2) {  # cheap numeric compare of references
print "refs 1 and 2 refer to the same thing\n";
}

关于perl - 如何检查 Perl 标量是否拥有对某个子例程的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13333336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com