gpt4 book ai didi

perl - 在 Perl 中测试 SUPER::methods 的分支分配

转载 作者:行者123 更新时间:2023-11-28 19:51:36 24 4
gpt4 key购买 nike

我即将完成研究Intermediate Perl书。

在第 18 章 对象销毁 中介绍了以下 DESTROY 方法定义:

# lib/Animal.pm
package Animal {
# ...
sub DESTROY {
my $self = shift;
if ($self->{temp_filename}){
my $fh = $self->{temp_fh};
close $fh;
unlink $self->{temp_filename};
}
print '[', $self->name, " has died.]\n";
}
# ...
}

# lib/Horse.pm
package Horse {
use parent qw(Animal)
# ...
sub DESTROY {
my $self = shift;
$self->SUPER::DESTROY if $self->can( 'SUPER::DESTROY' );
print "[", $self->name, " has gone off to the glue factory.]\n";
}
# ...
}

在几次尝试失败后,我根据this answer写了这个测试:

# t/Horse.t
#!perl -T

use strict;
use warnings;
use Test::More tests => 6;
use Test::Output;
# some other tests

# test DESTROY() when SUPER::DESTROY is not defined;
{
my $tv_horse = Horse->named('Mr. Ed');
stdout_is( sub { $tv_horse->DESTROY }, "[Mr. Ed has died.]\n[Mr. Ed has gone off to the glue factory.]\n",
'Horse DESTROY() when SUPER::DESTROY is defined');
}

{
my $tv_horse = Horse->named('Mr. Ed');
sub Animal::DESTROY { undef }
stdout_is( sub { $tv_horse->DESTROY }, "[Mr. Ed has gone off to the glue factory.]\n",
'Horse DESTROY() when SUPER::DESTROY is not defined');
}

我无法正确测试这两种情况的输出,因为方法重新定义 sub Animal::DESTROY { undef } 也影响了前一个 block 中的测试。

你知道有什么方法可以确保方法重定义按预期工作吗?

谢谢

最佳答案

这应该只设置删除/重新定义的子例程,直到封闭 block 结束,

{
# not needed when removing method
# no warnings 'redefine';

my $tv_horse = Horse->named('Mr. Ed');
# returns undef
# local *Animal::DESTROY = sub { undef };

# remove the mothod until end of the enclosing block
local *Animal::DESTROY;

# ..
}

关于perl - 在 Perl 中测试 SUPER::methods 的分支分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45914386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com