1

看下面的示例程序:

#! /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");
}
4

2 回答 2

4

伊萨_

if ($new_foo_bar->isa('Foo')) {
    say "Yep, it's a Foo";
} else {
    say "What happened?";
}
于 2013-01-24T19:08:59.670 回答
3

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

所以你可以写

say '$new_foo_bar is an object type Foo' if $new_foo_bar->isa('Foo')
于 2013-01-24T19:17:22.940 回答