Perl Moose 默认值未设置
我正在使用草莓 Perl Moose 2.0010
在类中:
package Cat;
use 5.010;
use strict;
use Moose;
has 'name', is => 'ro', isa => 'Str', default => 'Beauty';
#has 'age', is => 'ro';
has 'diet', is => 'rw', default => 'fish';
has 'birth_year', is => 'ro', isa=> 'Int',
default => 1997;
sub age
{
my $self = shift;
my $year = (localtime)[5] + 1900;
return $year - $self->birth_year();
}
在应用程序中:
use 5.010;
use strict;
use Cat;
my $kitty = Cat->new();
say 'I have a kitten named ', $kitty->name(), ' eats ', $kitty->diet(),
'in age ', $kitty->age();
输出:
使用未初始化的值 Cat.pm 第 16 行的减法 (-)。I 2011年有一只名叫吃的小猫 按任意键继续。 。 .
未设置默认值。
谢谢。
I am using strawberry perl
Moose 2.0010
In the class:
package Cat;
use 5.010;
use strict;
use Moose;
has 'name', is => 'ro', isa => 'Str', default => 'Beauty';
#has 'age', is => 'ro';
has 'diet', is => 'rw', default => 'fish';
has 'birth_year', is => 'ro', isa=> 'Int',
default => 1997;
sub age
{
my $self = shift;
my $year = (localtime)[5] + 1900;
return $year - $self->birth_year();
}
In the application:
use 5.010;
use strict;
use Cat;
my $kitty = Cat->new();
say 'I have a kitten named ', $kitty->name(), ' eats ', $kitty->diet(),
'in age ', $kitty->age();
Output:
Use of uninitialized value in
subtraction (-) at Cat.pm line 16. I
have a kitten named eats in age 2011
Press any key to continue . . .
The default value not set.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您今天的其他问题在您展示完整内容后显示了问题所在来源为
Cat.pm
。您定义了一个杂散的new
方法,该方法覆盖了Moose
提供的new
方法。删除那个杂散的new
方法,它就可以正常工作了。Your other question today shows what the problem is after you showed the full source to
Cat.pm
. You had a straynew
method defined which overrode thenew
method whichMoose
supplies. Remove that straynew
method, and it works just fine.$year
就可以了,(localtime)[5]
也是如此。问题是您的对象由于某种原因尚未初始化。也就是说, $self->birth_year() 返回未定义。
如果你看看你的输出,“有一只小猫,名字叫2011年吃”,你会错过名字、它吃什么,而且年龄是2011 - 0(或者如果我记得我的减法表的话,就是2011年)。由于 undef 被视为 0,因此在担心年龄计算之前您需要解决一些问题。
另外,我运行了你的代码,你要么没有告诉我们一些事情,要么这是你实际代码的释义。当我运行它时,我得到了预期的结果:“我有一只名叫 Beauty 的小猫在 1997 年出生,14 岁吃鱼”
我相信这是因为您没有包含尾随
1;
在Cat.pm
中,因此,它甚至无法编译。$year
is just fine, as is(localtime)[5]
.The problem is that your object hasn't been initialized for some reason. Namely, $self->birth_year() is coming back undefined.
If you look at your output, "have a kitten named eats in age 2011", you're missing the name, what it eats, and the age is 2011 - 0 (or just 2011 if I remember my subtraction tables). Since undef is treated as 0, you have issues to take care of before worrying about the age calculation.
Also, I ran your code, and you are either not telling us something, or this is a paraphrase of your actual code. When I ran it, I got the expected results: "I have a kitten named Beauty eats fish birth at 1997 aged 14"
One of the reasons I believe this is because you didn't include the trailing
1;
inCat.pm
, so as it is, it won't even compile.