看下面的示例程序:
#! /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");
}