#!/user/bin/perl use strict; use warnings; use Data::Dumper; use feature 'say'; sub matrix_write_file { my ($filename, $matrix) = @_; open(my $wfh, '>', $filename) or die "Could not open file '$filename' $!"; # print the whole thing with refs for my $aref ( @$matrix ) { say $wfh "@$aref"; } close $wfh or die "Could not close file '$filename' $!"; return; } sub matrix_read_file { my $matrix_name; my ($filename) = @_; open (my $rfh, $filename) or die "Could not open $filename: $!"; while (my $line = <$rfh>) { 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 $rfh or die "Could not close file '$filename' $!"; return $matrix_name; } my @matrix = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); my $filename = 'matrix.txt'; matrix_write_file($filename, \@matrix); print Dumper matrix_read_file($filename); __END__ $ perl test.pl $VAR1 = [ [ '1', '2', '3' ], [ '4', '5', '6' ], [ '7', '8', '9' ] ]; $ cat matrix.txt 1 2 3 4 5 6 7 8 9