2010年4月11日星期日

Re: [PerlChina] 关于Nested Object Destruction的一个问题

print '[', $self->name, " is being destroyed...]\n";

猜你的本意是:

print '[', ref $self, " is being destroyed...]\n";

改成如上这样就OK了,这是因为 $self 此时是 Barn, 没有 name 这个方法,直接就异常退出了。




2010/4/8 andy white <andyofwhite@gmail.com>
{ package Animal;
sub name {
my $either = shift;
ref $either
? $either->{Name}
: "an unnamed $either";
}
sub named {
my $class = shift;
my $name = shift;
my $self = { Name => $name, Color => $class->default_color };
bless $self, $class;
}

sub default_color { 'brown' }
sub DESTROY {
my $self = shift;
print '[', $self->name, " has died.]\n";
}
}
{ package Cow;
@ISA = qw( Animal );
}
{ package Barn;
sub new { bless [ ], shift }
sub add { push @{+shift}, shift }
sub contents { @{+shift} }
sub DESTROY {
my $self = shift;
print '[', $self->name, " is being destroyed...]\n";
for($self->contents) {
print ' ', $_->name, " goes homeless.\n";
}
}
}

my $barn = Barn->new;
$barn->add(Cow->named('Bessie'));
$barn->add(Cow->named('Gwen'));
print "Burn the barn:\n";
$barn = undef;
print "End of program.\n";

现在的程序的运行结果的是:
Burn the barn:
[Gwen has died.]
[Bessie has died.]
End of program.

当$barn = undef时,调用的是Animal的DESTROY方法。

我想要的结果是还要调用Barn的DESTROY方法(并且打印contents的内容),即
Burn the barn:
Barn=ARRAY(0x541c) is being destroyed...
  Bessie goes homeless.
  Gwen goes homeless.
[Gwen has died.]
[Bessie has died.]
End of program.

问题出在那里阿?那位帮忙看看吧!

--
您收到此邮件是因为您订阅了 Google 网上论坛的“PerlChina Mongers 讨论组”论坛。
要向此网上论坛发帖,请发送电子邮件至 perlchina@googlegroups.com
要取消订阅此网上论坛,请发送电子邮件至 perlchina+unsubscribe@googlegroups.com
若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。

--
您收到此邮件是因为您订阅了 Google 网上论坛的"PerlChina Mongers 讨论组"论坛。
要向此网上论坛发帖,请发送电子邮件至 perlchina@googlegroups.com。
要取消订阅此网上论坛,请发送电子邮件至 perlchina+unsubscribe@googlegroups.com。
若有更多问题,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问此网上论坛。

没有评论: