gpt4 book ai didi

perl - Scalar::Util 与 ref 函数

转载 作者:行者123 更新时间:2023-12-02 10:58:38 24 4
gpt4 key购买 nike

内置的ref($object)Scalar::Utilblessed($object)有什么区别?是否优先选择其中一个?

use strict;
use warnings;

use Scalar::Util qw(blessed isvstring);

my $object = foo->new();

print "Object is a " . blessed($object) . "\n";
print "Object is a " . ref($object) . "\n";

my $version = 5.00.03;

print "Version is a " . ref(\$version) . "\n";
if (isvstring($version)) {
print "Version is a VSTRING\n";
}

package foo;
sub new {
my $class = shift;
my $self = {};

bless($self, $class);
return $self;
}

最佳答案

根据 POD,blessed()仅适用于受祝福的引用(例如传递给 bless() 调用的引用)。

它返回undef其他所有内容,包括散列/数组引用,其中 ref()返回HASH/ARRAY (以及 perldoc ref 中描述的许多其他类型)。要获取引用类型,您当然可以调用 Scalar::Util::reftype .

至于是否应该使用一个而不是另一个,我认为这很大程度上取决于逻辑是什么。

  • 如果您只是想要将真正受祝福的引用文献与其他事物区分开来,blessed()提供了比 ref 更简洁的方法然后验证该值不是由 unblessed 引用返回的标准值。

    my $ref_type = ref($my_ref);
    print "USING REF: ";
    if ( $ref_type
    && $ref_type ne ref({})
    && $ref_type ne ref([])
    && $ref_type ne "SCALAR"
    # Could also use a hash with all allowed values of ref() instead
    && $ref_type !~ /^(CODE|REF|GLOB|...)$) {
    print "I am an object of class $ref_type\n";
    } else {
    print "I'm a reference of type $ref_type\n";
    }


    # vs...


    print "USING SCALAR_UTIL: ";
    my $ref_type = blessed($my_ref);
    print $ref_type ? "I am an object of class $ref_type\n"
    : "I am a reference of type " . reftype($my_ref) . "\n";
  • 如果您需要区分受祝福的引用和不同的受祝福的引用,那么单个 ref() call 比 blessed 的组合更简洁和reftype .

  • 正如 Eric Strom 的评论中所指出的,两种方法之间存在实际功能差异的一个极端情况是,有人创建了一个与 ref() 之一匹配的类。 hardcoded values (例如 bless [], 'HASH' - 在这种情况下,他们要么太愚蠢,要么太聪明)。

    my $sssft = bless [], 'HASH'; # sssft = someone_should_suffer_for_this
    ref_description_using_ref($sssft);
    ref_description_using_scalar_util($sssft);


    # OUTPUT:
    USING REF: I'm a reference of type HASH
    USING SCALAR_UTIL: I am an object of class HASH

免责声明:根据文档,当参数是祝福到类中的引用时(例如,它返回类名),两者之间应该没有区别。但我还没有检查“Scalar::Util”源来确认。

关于perl - Scalar::Util 与 ref 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4403013/

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