1

我正在使用PDL。如果给定的变量$foo可以是哈希引用、数组引用、标量或 piddle(可以为空或 null),我如何判断它是否是 piddle?

4

2 回答 2

3

检查某物是否属于某个类的典型方法是使用isa.

if( $thing->isa("PDL") ) { ... }

这尊重继承。只要$thing是 PDL 的子类(或说它是),上述内容就可以工作。这可以保护您免受自定义子类和 PDL 本身更改的影响。下面是一个例子。

use strict;
use warnings;
use v5.10;

package MyPDL;
our @ISA = qw(PDL);

package main;

use PDL;
use Scalar::Util qw(blessed);

my $stuff = pdl [1..10];

say blessed $stuff;                                   # PDL
say "\$stuff is a PDL thing" if $stuff->isa("PDL");   # true

my $bar = MyPDL->new([1..10]);
say blessed $bar;                                     # MyPDL
say "\$bar is a PDL thing" if $bar->isa("PDL");       # true

但是,方法调用不适用于非引用和未祝福的引用。如果你尝试,你会得到一个错误。您可以通过两种方式解决此问题。首先是用来eval BLOCK捕获错误,就像try在另一种语言中一样。

if( eval { $thing->isa("PDL") } ) { ... }

如果$thing不是对象,eval将捕获错误并返回 false。如果$thing是一个对象,它将调用isa它并返回结果。

缺点是这将捕获任何错误,包括来自isa. 很少见,但它会发生。为避免这种情况,请使用Scalar::Util 的blessed()来首先确定是否$thing是一个对象。

use Scalar::Util qw(blessed):

if( blessed $thing && $thing->isa("PDL") ) { ... }
于 2016-04-25T23:14:10.000 回答
3

您可以使用Scalar::Util来确定变量是否为:

  • 一个对象(使用blessed函数)
  • 一个引用,如果是,什么类型的引用(使用reftype函数)

您可以使用该isa方法来确定对象是特定类的实例还是继承自该类。

Piddles 是简单的 PDL 对象,即已经被祝福到PDL类中的东西,所以

$foo->isa('PDL')

$foo如果是 piddle将返回 true 。

全部一起:

use strict;
use warnings 'all';
use 5.010;

use PDL;
use Scalar::Util qw(blessed reftype);

my $scalar   = 19;
my $arrayref = [ qw(foo bar) ];
my $hashref  = { baz => 'qux' };
my $piddle   = pdl [ 1..10 ];

foreach my $item ($scalar, $arrayref, $hashref, $piddle) {
    my $reftype;

    if ( defined(blessed($item)) ) {
        say 'piddle' if $item->isa('PDL');
    }
    elsif ( defined($reftype = reftype($item)) ) {
        say $reftype;
    }
    else {
        say 'Not a reference';
    }
}

输出:

Not a reference
ARRAY
HASH
piddle
于 2016-04-25T21:59:48.583 回答