gpt4 book ai didi

perl - 使用 Perl 的 Class::Struct 构建对象时如何引用该对象?

转载 作者:行者123 更新时间:2023-12-04 23:33:15 26 4
gpt4 key购买 nike

我是面向对象 Perl 的新手,我必须在同一对象的另一个子程序中访问同一对象的成员变量。示例代码在这里:

use Class::Struct;

struct Breed =>
{
name => '$',
cross => '$',
};

struct Cat =>
[
name => '$',
kittens => '@',
markings => '%',
breed => 'Breed',
breed2 => '$',

];

my $cat = Cat->new( name => 'Socks',
kittens => ['Monica', 'Kenneth'],
markings => { socks=>1, blaze=>"white" },
breed => { name=>'short-hair', cross=>1 },
** //breed2 => sub { return $cat->breed->name;}**

);

print "Once a cat called ", $cat->name, "\n";
**print "(which was a ", $cat->breed->name, ")\n";**
print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";

但我不确定如何在breed2 的子程序中使用$cat->breed->name ?有人可以帮我弄这个吗。

最佳答案

breed2中的问题是您试图引用尚 undefined variable 。看起来它是同名的,但它不是您正在创建的对象。这有点鸡和蛋的问题。

无论如何,我不太确定您是否想要在该插槽中使用这样的匿名子程序。你是
只是想缩短 $cat->breed->name$cat->breed2 ?您可以从 undef 开始在 breed2并在构造函数之后立即更改其值,因为那时您将拥有对该对象的引用。然而,即使你在那里放置了一个子程序,你也必须取消引用它:

my $cat = Cat->new( name     => 'Socks',
kittens => ['Monica', 'Kenneth'],
markings => { socks=>1, blaze=>"white" },
breed => { name=>'short-hair', cross=>1 },
breed2 => undef,

);
$cat->breed2( sub { $cat->breed->name } );

print "Once a cat called ", $cat->name, "\n";
print "(which was a ", $cat->breed2->(), ")\n";
print "had two kittens: ", join(' and ', @{$cat->kittens}), "\n";

关于perl - 使用 Perl 的 Class::Struct 构建对象时如何引用该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2103137/

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