gpt4 book ai didi

perl - 检查 Perl 数据引用类型

转载 作者:行者123 更新时间:2023-12-05 00:23:27 29 4
gpt4 key购买 nike

在 Perl 中检查引用类型时,为什么最好使用 constant附注:

use constant HASH => ref {};

die "I expect a hashref" unless $ref_type eq HASH;

比硬编码字符串:
die "I expect a hashref" unless $ref_type eq 'HASH';

有什么优点和缺点(如果有的话)?

最佳答案

我可以看到的主要优点是,使用 strict 'subs'实际上,如果标识符拼写错误,则会引发错误,而字符串拼写错误则不会引起注意。

例如,如果我写

use strict;
use warnings;

my $data = {};

die "I expect a hashref" unless ref $data eq 'HSH';

然后我的代码编译没有问题,但不会正确运行。但如果我有
use strict;
use warnings;

use constant HASH => ref {};

my $data = {};

die "I expect a hashref" unless ref $data eq HSH;

然后我被告知
Bareword "HSH" not allowed while "strict subs" in use

在程序开始运行之前。

这是一个合适的地方提到 reftype功能由 Scalar::Util 提供.
ref运算符将返回 HASH如果它应用于简单的哈希引用。但是,如果该引用有幸将其转换为 Perl 对象, ref将返回引用被祝福到的类的名称。

对象通常是一个受祝福的散列引用,但它可以由对任何类型数据的引用构成——包括子例程和类型团。显然是一个简单的 ref不会帮助我们发现用于创建对象的底层 Perl 数据类型,因此 reftype被写来填补这个空白。

考虑这个 Perl 程序
use strict;
use warnings;

use Scalar::Util 'reftype';

my $data = { };

print "Plain hash reference\n";
printf " ref => %s\n", ref $data;
printf " reftype => %s\n", reftype $data;

bless $data, 'Class';

print "\nBlessed hash reference\n";
printf " ref => %s\n", ref $data;
printf " reftype => %s\n", reftype $data;

输出
Plain hash reference
ref => HASH
reftype => HASH

Blessed hash reference
ref => Class
reftype => HASH

如您所见, refreftype对于简单的散列引用返回相同的结果,而只有 reftype可以在blessed引用的类后面看到它的底层数据类型是不变的。

关于perl - 检查 Perl 数据引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28137807/

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