Transpose in perl

Viewed 15061

I have started learning perl and like to try out new things.

I have some problem in text processing. I have some text of the form,

0 1 2 3 4 5 6 7 8 9 10

6 7 3 6 9 3 1 5 2 4 6

I want to transpose this text. Like, I want to make rows as columns ans columns as rows. Id there a way to do this in perl?

Thank you all.

9 Answers

I ran across this question while searching for a way to transpose an AoA I built by reading a file, but of course, this solution will still work for any AoA, and it doesn't require the array references have equal numbers of elements. I know this is an old question, but as I'm still learning, it would be awesome to have some critique/examples of how to improve my solution.

my $max_rows = 0;
foreach my $line (@copy) {
    my $ref = ();
    push @$ref, split(/\s+/, $line);
    my $rows = scalar(@$ref);
    $aoa[$i] = \@$ref;
    $i++;
    if ($rows > $max_rows) {
        $max_rows = $rows;
    }
}

for (my $i = 0; $i <= $max_rows; $i++) {
    my @aoa_t = ();
    for (my $k = 0; $k <= $#aoa; $k++) {
        if ($aoa[$k]->[$i]) {
            push @aoa_t, $aoa[$k]->[$i];
        } else {
            push @aoa_t, " ";
        }
        print " @aoa_t\n";
    }
    if ($aoa_t[0] eq " ") {
        last;
    } else {
        $t_aoa[$i] = \@aoa_t;
    }
}

It worked very well for a file with 200+ lines of data in space delimited format. Any feedback is appreciated, if that is appropriate in this forum. Regards.

Related