#!/usr/bin/perl use strict; use warnings; use Inline::Files; use Data::Dumper; my @matrix; while (defined (my $line=)) { next unless $line =~ /^\s*\d/; # skip blanks or comments my @row = split ' ',$line; push @matrix, [@row]; } print "input matrix:\n"; dump_matrix(\@matrix); my $transposed_ref = transpose_matrix (\@matrix); print "\ntransposed matrix:\n"; dump_matrix($transposed_ref); # a "ragged" matrix would have differing number of # elements in each row. This won't work for that. sub transpose_matrix # only for "non-ragged" matricies { my $AoAref = shift; my @input_matrix = @$AoAref; #local copy to destroy my @result_matrix; while (defined $input_matrix[0][0]) { my @new_row; foreach my $row_ref (@input_matrix) { push @new_row, (shift @$row_ref); } push @result_matrix, [@new_row]; } # at this point, @input_matrix is an array of references # to empty rows, rows still "exist" but have no data in them print "At end of transpose, local copy of input_matrix is like this:\n"; print Dumper \@input_matrix; return \@result_matrix; } sub dump_matrix { my $AoAref = shift; foreach my $row_ref (@$AoAref) { print "@$row_ref\n"; } } =Prints input matrix: 1 2 3 4 5 6 7 8 9 At end of transpose, local copy of input_matrix is like this: $VAR1 = [ [], [], [] ]; transposed matrix: 1 4 7 2 5 8 3 6 9 =cut __DATA__ #title line - (skipped it with $nextUnless) #title line - (skipped it with $nextUnless) 1 2 3 4 5 6 7 8 9 #### #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $file1=<)) { next unless $line =~ /^\s*\d/; # skip blanks or comments my @row = split ' ',$line; push @matrix, [@row]; } return \@matrix; } sub dump_matrix { my $AoAref = shift; foreach my $row_ref (@$AoAref) { print "@$row_ref\n"; } } sub transpose_matrix # only for "non-ragged" matricies { my $AoAref = shift; my @input_matrix = @$AoAref; #local copy to destroy my @result_matrix; while (defined $input_matrix[0][0]) { my @new_row; foreach my $row_ref (@input_matrix) { push @new_row, (shift @$row_ref); } push @result_matrix, [@new_row]; } # at this point, @input_matrix is an array of references # to empty rows, rows still "exist" but have no data in them return \@result_matrix; } __END__ We have read a total of: 2 matricies: 1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 20 21 22 Element[0,1,2]: 6 Element[1,2,1]: 18 Now transpose matrix #2: 1 2 3 4 5 6 7 8 9 11 14 17 20 12 15 18 21 13 16 19 22