Nathan Merrill
Nathan Merrill

Reputation: 8386

Iterating through 2 matrices in perl

I am trying to write a program that sums two matrices (implemented as a double array) in perl.

I'm sure there's some function that can do it for me, but this is for a homework assignment, so I need to do it myself.

My problem, I'm sure, is in the syntax. Can you explain what I am doing wrong?

sub matrix_add {
  my @matrix1 = $_[0];
  my @matrix2 = $_[1];
  for my $x (0 .. $#matrix1){
    my @line1 = @matrix1[$x];
    my @line2 = @matrix2[$x];
    for my $y (0.. $#line1){
        @line1[$y] += @line2[$y];
    }
  }
  return @matrix1
}

I am not getting any errors, but when I print out the array, I'm printing out what I think are references:

 ARRAY(0x508a24)ARRAY(0x508b44)

Additional info:

I'm declaring the matrices like such:

my @matrix = ( 
 [0, 1], 
 [2, 3] 
 ); 

and printing them out them using a double for-each.

Upvotes: 2

Views: 30

Answers (1)

mpapec
mpapec

Reputation: 50647

You can only pass array reference to function so

sub matrix_add {
  my ($matrix1, $matrix2) = @_;

and use @$matrix1, @$matrix2 later on in the function.

Upvotes: 4

Related Questions