#!/user/bin/perl use strict; use warnings; use Data::Dumper; use feature 'say'; use IO::All -utf8; # use Benchmark qw(:all) ; # WindowsOS use Benchmark::Forking qw( timethese cmpthese ); # UnixOS 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); my (@row) = split (/\s+/, $line); push (@{$matrix_name}, \@row); } close $rfh or die "Could not close file '$filename' $!"; return $matrix_name; } sub writeMatrix2File{ my ( $filename , $matrix ) = @_; my $iol = io($filename)->lock; while (defined(my $line = shift @$matrix)) { # io($filename)->appendln(join ' ', map "$_", @$line); $iol->println(join ' ', map "$_", @$line) } $iol->unlock; } sub readMatrixFromFile{ my $matrix; my ( $filename ) = @_; my @lines = io($filename)->chomp->slurp; while (defined (my $line = shift @lines)){ my (@row) = split (/\s+/, $line); push (@{$matrix}, \@row); } return $matrix; } sub manual { my $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; my $filename = 'matrix.txt'; matrix_write_file($filename, $matrix); matrix_read_file($filename); } sub module { my $matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; my $filename = 'matrix.txt'; writeMatrix2File($filename, $matrix); readMatrixFromFile($filename); } manual(); module(); my $results = timethese(1000000, { Manual => \&manual, Module => \&module, }, 'none'); cmpthese( $results ); __END__ :~/PerlMonks$ perl matrix.pl Rate Module Manual Module 1895/s -- -84% Manual 12054/s 536% --