-1

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.

Weiyan
  • 1,116
  • 3
  • 14
  • 25

2 Answers2

4

Your other question today shows what the problem is after you showed the full source to Cat.pm. You had a stray new method defined which overrode the new method which Moose supplies. Remove that stray new method, and it works just fine.

Community
  • 1
  • 1
unpythonic
  • 4,020
  • 19
  • 20
  • @Weiyan - if you want to override `new()` using Moose, then look at `BUILDARGS` and `BUILD` : http://search.cpan.org/dist/Moose/lib/Moose/Manual/Construction.pod – plusplus Jun 22 '11 at 08:39
3

$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; in Cat.pm, so as it is, it won't even compile.

unpythonic
  • 4,020
  • 19
  • 20