请看以下示例程序:
#! /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");
}
答案 0 :(得分:4)
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')