waldm
New User
May 30, 2014, 5:17 AM
Post #1 of 3
(4898 views)

Moose and arrays

Can't Post


Hi, I have previous experience in other programming languages (Java, C#, Python), and just started learning Perl a couple of days ago. I'm trying to write a basic calculator, and so far have the following code: main.pl
use Calculator; my $calculator = Calculator>new(); $calculator>add(1, 2); $calculator>add(3, 2); my $calculations = $calculator>calculations; print "The calculator has [@$calculations].\n"; Calculation.pm
package Calculation; use Moose; has 'expression' => ( is => 'rw', isa => 'Str', required => 1, ); has 'result' => ( is => 'rw', isa => 'Num', required => 1, ); 1; Calculator.pm
package Calculator; use Moose; use Calculation; has 'calculations' => ( is => 'rw', isa => 'ArrayRef[Calculation]', ); sub add { my $self = shift; my @calculations = $self>calculations; my $x = $_[0]; my $y = $_[1]; my $calculation = Calculation>new( expression => "$x+$y", result => $x + $y); push(@calculations, $calculation); $self>calculations(\@calculations); } 1; but the following error occurs:
Attribute (calculations) does not pass the type constraint because: Validation failed for 'ArrayRef[Calculation]' with value [ undef, Calculation={ expression: "1+2", result: 3 } ] at accessor Calculator::calculations (defined at Calculator.pm line 6) line 4. Calculator::calculations('Calculator=HASH(0x198ebd0)', 'ARRAY(0x25bc740)') called at Calculator.pm line 23 Calculator::add('Calculator=HASH(0x198ebd0)', 1, 2) called at main.pl line 4 If I change the line push(@calculations, $calculation); to $calculations[0] = $calculation; , then it works, but obviously this will only allow me to store one calculation. Does anyone know what the problem is here? Thanks p.s. I tried to use the [perl] tag instead of the code tag, but it didn't appear to work.
