Page 53      All Pages  All Books
that is reference counted, not the name.)
Example 2.1: Reading a Matrix from a File
sub matrix_read_file { my ($filename) = @_;
open (F, $filename) || die "Could not open $filename: $!"; while ($line = <F>) { chomp($line);
next if $line =~ /^\s*$/; # skip blank lines if ($line =~ /^([A-Za-z]\w*)/) {
$matrix_name = $1; } else {
my (@row) = split (/\s+/, $line);
push (@{$matrix_name}, \@row;) # insert the row-array into
# the outer matrix array } }
close(F); }
Now let us use this array-of-arrays structure to multiply two matrices. In case you have forgotten how matrix multiplication works, the product of two matrices Amn (m rows, n columns) and Bnp is defined as
^j = 2 Aft . Ekj
The element (i, j) of the matrix product is the sum of successive pairs of elements taken from the i th row of A and the jth column of B. Translated into Perl, it looks like Example 2.2.
Example 2.2: Matrix Multiply
sub matrix_multiply {
my ($r_mat1, $r_mat2) = @_; # Taking matrices by reference
my ($r_product);                                        # Returing product by reference
my ($r1, $c1) = matrix_count_rows_cols ($r_mat1);
my ($r2, $c2) = matrix_count_rows_cols ($r_mat2);
die "Matrix 1 has $c1 columns and matrix 2 has $r2 rows."
. " Cannot multiply\n" unless ($c1 == $r2); for ($i = 0; $i < $r1; $i++) {
for ($j = 0; $j < $c2; $j++) { $sum = 0; for ($k = 0; $k < $c1; $k++) {
$sum += $r_mat1->[$i][$k] * $r_mat2->[$k][$j]; }
$r_product->[$i][$j] = $sum; }

Page 53      All Pages  All Books