exercism-perl5

Repository for my Perl 5 Exercism exercises
git clone git://git.samirparikh.com/exercism-perl5
Log | Files | Refs | README

Matrix.pm (1392B) - raw


      1 package Matrix;
      2 use strict;
      3 use warnings;
      4 use Exporter qw<import>;
      5 our @EXPORT_OK = qw<row column>;
      6 
      7 sub define_matrix {
      8     my @matrix;
      9     # shift is just the parameter that was passed to the subroutine
     10     # split on the newline
     11     my @lines = split /\n/, shift;
     12     # push into the matrix a reference to an array which represents
     13     # each row.  Elements of the array are found by splitting on
     14     # blank space
     15     push @matrix, [split / /] foreach (@lines);
     16     return @matrix;
     17 }
     18 
     19 # $input is a reference to a hash with two keys:
     20 # index, which asks for a row or column, and
     21 # string, which represents the matrix
     22 
     23 sub row {
     24   my ($input) = @_;
     25   my $index  = $input->{'index'};
     26   my @matrix = define_matrix($input->{'string'});
     27   # since we are returning a row, $index-1 is the row within @matrix
     28   # we need to return.  In this case, we are returning a reference to
     29   # an array which contains the element of the row
     30   return $matrix[$index - 1];
     31 }
     32 
     33 sub column {
     34   my ($input) = @_;
     35   my $index  = $input->{'index'};
     36   my @matrix = define_matrix($input->{'string'});
     37   my @column;
     38   # each row of the matrix is represented by an array.  $row is a
     39   # reference to that array.  To get the column, we use [$index-1].
     40   foreach my $row (@matrix) {
     41       push @column, $row->[$index - 1];
     42   }
     43   # we need to return a reference to the array containing the column
     44   return \@column;
     45 }
     46 
     47 1;