Reputation: 17
So i am trying to read a 2-d matrix in from a file so that I can multiply two matrices together. I can get the individual rows of the matrix to print, but I can't get the subroutine to return the entire matrix. I'm not sure what I'm doing wrong. I pasted the test matrix from the file I am using:
12345
67890
34567
The output I get is:
final matrix is: ##THIS IS WHAT I AM TRYING TO PRINT OUT BUT I GET NOTHING
row is:12345
row is:67890
row is:34567
Upvotes: 1
Views: 98
Reputation: 40768
Here is an example:
use feature qw(say);
use strict;
use warnings;
use Data::Dumper;
{
print "Enter filename: ";
chomp(my $matrix_file = <STDIN>);
say "final matrix is:";
my $matrix = matrix_read_file($matrix_file);
print Dumper($matrix);
}
sub matrix_read_file {
my ($filename) = @_;
my @matrix;
open (my $F, '<', $filename) or die "Could not open $filename: $!";
while (my $line =<$F> ) {
chomp $line;
next if $line =~ /^\s*$/; # skip blank lines
my @row = split /\s+/, $line;
push @matrix, \@row;
}
close $F;
return \@matrix;
}
If you give the following input file:
1 2 3 4 5
6 7 8 9 10
The program outputs:
final matrix is:
$VAR1 = [
[
'1',
'2',
'3',
'4',
'5'
],
[
'6',
'7',
'8',
'9',
'10'
]
];
Upvotes: 1