use strict 'vars'; use strict 'subs'; use warnings; my @matrix1=( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); my @matrix2=( [2, 4, 6], [1, 3, 5], [7, 8, 9] ); print "matrix1=\n"; for (my $i=0;$i le 2;$i++) { for (my $j=0;$j le 2;$j++) { print $matrix1[$i][$j]," "; } print "\n"; } print "matrix2=\n"; for (my $i=0;$i le 2;$i++) { for (my $j=0;$j le 2;$j++) { print $matrix2[$i][$j]," "; } print "\n"; } my @product=matrix_multiply(@matrix1,@matrix2); print "product=\n"; for (my $i=0;$i le 2;$i++) { for (my $j=0;$j le 2;$j++) { print $product[$i][$j]," "; } print "\n"; } sub matrix_multiply { my ($r_mat1,$r_mat2)=@_; my ($r_product); my ($r1,$c1)=matrix_count_rows_cols($r_mat1); my ($r2,$c2)=matrix_count_rows_cols($r_mat2); print $c1,$c2,"\n"; print $r1,$r2,"\n"; die "matrix 1 has $c1 columns and matrix 2 has $r2 rows>" . " Cannot multiply\n" unless ($c1==$r2); for (my $i=0;$i<$r1;$i++) { for (my $j=0;$j<$c2;$j++) { my $sum=0; for (my $k=0;$k<$c1;$k++) { $sum+=$r_mat1->[$i][$k]*$r_mat2->[$k][$j]; } $r_product->[$i][$j]=$sum; } } $r_product; } sub matrix_count_rows_cols { my ($r_mat)=@_; my $num_rows=@$r_mat; my $num_cols=@{$r_mat->[0]}; ($num_rows,$num_cols); }