Not_yetta_Monk has asked for the wisdom of the Perl Monks concerning the following question:

OK here it goes. Im pretty new to perl but I've managed so far on the simple stuff. My question is this, i have a text file with 78 columns and 4843 rows. I need to input this file into another program to analyze the data. My only problem is i need the columns switched with the rows effectively making 4843 columns and 78 rows. Can this be done with my novice skills? Thanks in advance for the wisdom.

Replies are listed 'Best First'.
Re: switch columns and rows
by ikegami (Patriarch) on Oct 30, 2007 at 17:16 UTC

    It's really just a matter of inverting the order of the indexes.

    From an earlier thread (How to swap rows with columns?),

    my @data; while (<>) { my @fields = split ' '; my $col = $. - 1; for my $row (0..$#fields) { $data[$row][$col] = $fields[$row]; } }

    Tested.

Re: switch columns and rows
by dwm042 (Priest) on Oct 30, 2007 at 17:32 UTC
    Something like this can work:

    #!/bin/perl use warnings; use strict; my @array; my $rows = 0; my $columns = 0; while(<DATA>) { chomp; $rows = length($_); for ( my $j = 0; $j < $rows; $j++ ) { $array[$columns][$j] = substr($_, $j, 1); } $columns++; } for ( my $m = 0; $m < $rows; $m++ ) { for ( my $k = 0; $k < $columns ; $k++ ) { print $array[$k][$m]; } print "\n"; } __DATA__ 12345 12345 12345 12345 12345 12345 12345 12345 12345 12345 12345 12345 12345
    With the output:

    C:\Code>perl swap.pl 1111111111111 2222222222222 3333333333333 4444444444444 5555555555555
    But it has to be noted, I think this topic has been touched on at least twice in the last month.

Re: switch columns and rows
by gamache (Friar) on Oct 30, 2007 at 18:15 UTC
    One more solution won't hurt anyone.
    sub transpose { my @t; for (my $i; $i<@_; $i++) { for (my $j; $j<@{$_[$i]}; $j++) { $t[$j][$i] = $_[$i][$j] } } wantarray ? @t : \@t } my @matrix = ( [1, 2, 3, 4], [5, 6, 7, 8] ); my @transposed = transpose (@matrix);