Transpose a Matrix (Arrays or Arrays)
While Perl arrays can only be one-dimensionals, each value can be a reference to another array and then it could look like as if it was a 2 or more dimansional array.
If each element of an array is a reference to another array, and if each one of the internal arrays has the same number of elements then it will look like a matrix.
A matrix can be transposed. (Replace the rows by arrays.)
examples/transpose_matrix.pl
use 5.010; use strict; use warnings; use Data::Dump qw(dump); my @matrix = ( [ 'name11', 'name12', 'name13', 'name14' ], [ 'name21', 'name22', 'name23', 'name24' ], [ 'name31', 'name32', 'name33', 'name34' ], ); say dump \@matrix; my @tr; for my $row (0..@matrix-1) { for my $col (0..@{$matrix[$row]}-1) { $tr[$col][$row] = $matrix[$row][$col]; } } say dump \@tr;
The result looks like this, printing the before and after versions.
examples/transpose_matrix.txt
[ ["name11", "name12", "name13", "name14"], ["name21", "name22", "name23", "name24"], ["name31", "name32", "name33", "name34"], ] [ ["name11", "name21", "name31"], ["name12", "name22", "name32"], ["name13", "name23", "name33"], ["name14", "name24", "name34"], ]
Published on 2019-05-09