如何确定 Perl 中祝福引用的类型? [英] How can I determine the type of a blessed reference in Perl?

查看:51
本文介绍了如何确定 Perl 中祝福引用的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Perl 中,对象只是对已被祝福到特定类的任何基本 Perl 数据类型的引用.当你在一个非祝福的引用上使用 ref() 函数时,你会被告知引用指向的数据类型.但是,当您对一个受祝福的引用调用 ref() 时,您将返回该引用被祝福到的包的名称.

In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class. When you use the ref() function on an unblessed reference, you are told what data type the reference points to. However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into.

我想知道祝福引用的实际基础类型.我如何确定这一点?

I want to know the actual underlying type of the blessed reference. How can I determine this?

推荐答案

Scalar::Util::reftype() 是最干净的解决方案.Scalar::Util 模块在 5.7 版中添加到 Perl 核心,但可用于来自 CPAN 的旧版本(5.004 或更高版本).

Scalar::Util::reftype() is the cleanest solution. The Scalar::Util module was added to the Perl core in version 5.7 but is available for older versions (5.004 or later) from CPAN.

您也可以使用 UNIVERSAL::isa() 进行探测:

You can also probe with UNIVERSAL::isa():

$x->isa('HASH')             # if $x is known to be an object
UNIVERSAL::isa($x, 'HASH')  # if $x might not be an object or reference

显然,您还必须检查 ARRAYSCALAR 类型.从 Perl 5.003 开始​​,UNIVERSAL 模块(用作所有对象的基类)一直是核心的一部分.

Obviously, you'd also have to check for ARRAY and SCALAR types. The UNIVERSAL module (which serves as the base class for all objects) has been part of the core since Perl 5.003.

另一种方法——简单但有点脏——是将引用字符串化.假设该类没有重载字符串化,你会得到类似于 Class=HASH(0x1234ABCD) 的东西,你可以解析它以提取底层数据类型:

Another way -- easy but a little dirty -- is to stringify the reference. Assuming that the class hasn't overloaded stringification you'll get back something resembling Class=HASH(0x1234ABCD), which you can parse to extract the underlying data type:

my $type = ($object =~ /=(.+)\(0x[0-9a-f]+\)$/i);

这篇关于如何确定 Perl 中祝福引用的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆