Perl查看对象是否是特定类的成员

时间:2013-01-24 19:06:16

标签: perl oop

请看以下示例程序:

#! /usr/bin/env perl
#

use 5.10.0;
use strict;
use warnings;


my $new_foo = Foo->new();
my $new_foo_bar = Foo::Bar->new();

say '$new_foo is an object type ' . ref $new_foo;
say '$new_foo_bar is an object type ' . ref $new_foo_bar;


package Foo;

sub new {
    my $class = shift;

    my $self = {};
    bless $self, $class;
    return $self;
}

package Foo::Bar;
use base qw(Foo);

返回:

$new_foo is an object type Foo
$new_foo_bar is an object type Foo::Bar

有没有办法测试$new_foo_bar是否也是Foo的对象类型?我知道它是。我可以利用我的命名约定,并简单地假设任何具有与`/ ^ Foo(:)/匹配的引用类型的东西都是该对象类型,但只有遵循该约定才会出现这种情况。是否有官方的Perl方法来确定对象是否属于该对象类型?

这样的事情:

if ( is_a_memeber_of( $my_object_ref, "Foo" ) {
    say qq(\$my_object_ref is a member of "Foo" even though it might also be a sub-class of "Foo");
}
else {
    say qq(\$my_object_ref isn't a member of "Foo");
}

2 个答案:

答案 0 :(得分:4)

isa

if ($new_foo_bar->isa('Foo')) {
    say "Yep, it's a Foo";
} else {
    say "What happened?";
}

答案 1 :(得分:3)

每个Perl类都继承自内置的UNIVERSAL类,该类包含一个名为isa的方法,该方法检查对象是否继承自给定的类。

所以你可以写

say '$new_foo_bar is an object type Foo' if $new_foo_bar->isa('Foo')