gpt4 book ai didi

perl - 在 Perl 中本地更改类的属性

转载 作者:行者123 更新时间:2023-12-01 00:49:08 25 4
gpt4 key购买 nike

我在我的一个 Perl 脚本中遇到了一个奇怪的问题。我有一个 Perl 对象。在某个范围内,我希望更改对象属性之一,但我希望该属性在离开范围后恢复为旧值。

例子:

my $object = Object->new('name' => 'Bob');
{
# I know this doesn't work, but it is the best way
# I can represent what I amd trying to do.
local $object->name('Lenny');

# Prints "Lenny"
print $object->name();
}

# Prints "Bob"
print $object->name();

有没有办法实现这样的目标?

最佳答案

这可能不像您要求的那么多封装,但您可以 local -ize 散列的属性。这输出 "CarlLennyCarl"

sub Object::new { bless { _name => $_[1] }, $_[0] } }
sub Object::name { $_[0]->{_name} }

my $obj = Object->new("Carl");
print $obj->name;
{
local $obj->{_name} = "Lenny";
print $obj->name;
}
print $obj->name;

您也可以 local -ize 整个方法。这也输出 "CarlLennyCarl" :
sub Object::new { bless { _name => $_[1] }, $_[0] } }
sub Object::name { $_[0]->{_name} }

my $obj = Object->new("Carl");
print $obj->name;
{
local *Object::name = sub { "Lenny" };
print $obj->name;
}
print $obj->name;

关于perl - 在 Perl 中本地更改类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384605/

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