diff --git a/Build.PL b/Build.PL index 3d036ea..03df474 100644 --- a/Build.PL +++ b/Build.PL @@ -11,6 +11,7 @@ my $builder = Module::Build->new( license => 'perl', build_requires => { 'Test::Most' => 0, + 'File::Temp' => 0, 'File::Spec' => 0, }, configure_requires => { 'Module::Build' => 0.38 }, diff --git a/CHANGES b/CHANGES index 632b972..9848fd2 100644 --- a/CHANGES +++ b/CHANGES @@ -1,3 +1,6 @@ + + * Add save_to_file/new from file (Alberto Simões) + Changes in v2.11 - Jonathan "Duke" Leto January 2014 -------------------------- diff --git a/CREDITS b/CREDITS index 922e611..bb2e00d 100644 --- a/CREDITS +++ b/CREDITS @@ -17,6 +17,8 @@ Many people deserve recoginition for their help with Math::MatrixReal: * Mike South for the new_from_cols() and new_from_rows() functions that were integrated from Math::MatrixReal::Ext1 +* Alberto Simões for contributions. + * Everybody involved with CPAN Testers, thanks guys/gals! diff --git a/lib/Math/MatrixReal.pm b/lib/Math/MatrixReal.pm index ecc5fd7..f1deb77 100644 --- a/lib/Math/MatrixReal.pm +++ b/lib/Math/MatrixReal.pm @@ -21,7 +21,7 @@ require Exporter; $VERSION = '2.11'; use overload - '.' => '_concat', + '.' => '_concat', 'neg' => '_negate', '~' => '_transpose', 'bool' => '_boolean', @@ -2813,6 +2813,40 @@ sub _min_column { } +sub save_to_file { + my ($matrix, $filename) = @_; + + open my $fh, ">", $filename or + croak "Math::MatrixReal save_to_file: could not create file '$filename': $!"; + + # probably faster than creating a full string in memory + my ($rows, $cols) = $matrix->dim(); + + for my $r (0..$rows-1) { + for my $c (0..$cols-1) { + print $fh $matrix->[0][$r][$c]; + print $fh "\t" unless $c == $cols-1; + } + print $fh "\n"; + } + close $fh; +} + +sub new_from_file { + my ($class, $filename) = @_; + my $m = []; + + open my $fh, "<", $filename or + croak "Math::MatrixReal new_from_file: could not open file '$filename': $!"; + + while (<$fh>) { + chomp; + push @$m, [split /\s+/]; + } + + return $class->new_from_rows($m); +} + ######################################## # # diff --git a/t/save2file.t b/t/save2file.t new file mode 100644 index 0000000..eede3b2 --- /dev/null +++ b/t/save2file.t @@ -0,0 +1,34 @@ +use Test::More tests => 4; +use File::Spec; +use lib File::Spec->catfile("..","lib"); +use Math::MatrixReal; +use File::Temp 'tempfile'; + +do 'funcs.pl'; + +my $matrix = Math::MatrixReal->new_from_string(<<"MATRIX"); + + [ 1 5 9 ] + [ 2 6 10 ] + [ 3 7 11 ] + [ 4 8 12 ] + +MATRIX + +my ($fh, $filename) = tempfile(); + +$matrix->save_to_file($filename); + +close $fh; + +ok -f $filename, "save_to_file: created output file"; + +my $other = Math::MatrixReal->new_from_file($filename); + +isa_ok $other, 'Math::MatrixReal', "new_from_file: created a Math::MatrixReal object"; + +ok_matrix($matrix, $other, "new_from_file: loaded matrix is the same!"); + + +assert_dies(sub { Math::MatrixReal->new_from_file(File::Temp::mktemp("tmpfileXXXXX")) }, + "new_from_file: dies on non-existent file");