Perl:如何在没有警告的情况下在END {}中调用对象方法? [英] Perl: How can I call object methods inside END {} without warning?
本文介绍了Perl:如何在没有警告的情况下在END {}中调用对象方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
package JustTesting;
use strict;
use warnings;
sub new {
my $self = {};
bless($self, shift);
END { $self->goodbye() };
return $self;
}
sub goodbye {
print "Goodbye.\n";
}
package main;
my $this = JustTesting->new();
输出:
变量"$ self"将不会在./test第10行共享.
再见.
Variable "$self" will not stay shared at ./test line 10.
Goodbye.
显然,它可以工作,我可以在END块内使用no
warnings
禁止显示警告.但我想知道是否有更好的方法
该怎么做.
Apparently it works and I can suppress the warning with no
warnings
inside the END block. But I wonder if there is a better way
how to do this.
我尝试使用像这样的匿名子:
I tried using an anonymous sub like this:
my $cleanup = sub { $self->goodbye() };
END { $cleanup->() };
然后像这样:
END { sub { $self->goodbye() }->() };
但是我总是收到同样的警告.
But I always get the same warning.
推荐答案
您最有可能想要 END
.另请参见有关perltoot中的析构函数的部分.
You most likely want DESTROY
instead of END
. See also the section on destructors in perltoot.
package JustTesting;
use strict;
use warnings;
sub new {
my $self = {};
bless($self, shift);
return $self;
}
sub goodbye {
print "Goodbye.\n";
}
sub DESTROY {
my ($self) = @_;
$self->goodbye()
};
package main;
{
say "entering scope";
my $this = JustTesting->new();
say "leaving scope";
}
say "left scope";
输出:
entering scope
leaving scope
Goodbye.
left scope
这篇关于Perl:如何在没有警告的情况下在END {}中调用对象方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文