在 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
如您所见,
ref
和 reftype
对于简单的散列引用返回相同的结果,而只有 reftype
可以在blessed引用的类后面看到它的底层数据类型是不变的。
关于perl - 检查 Perl 数据引用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28137807/