my $inp=' 1 2 3 4 5 6 a b c x y z '; my @data; my @elem = grep length, split /\s+/, $inp; my $rows = () = $inp =~/(?<=^)\w/msg; my $cols = @elem / $rows; for my $col (0..$cols-1) { push @data, [ map $elem[$col + $cols*$_], 0..$rows-1 ] } # print the matrix print "@$_\n" for @data;