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

Hi there , I have a file that I am reading which look like this :
1 cow MM 2 cat DD 3 fly SS
I want to read it and output like this :
1 2 3 cow cat fly MM DD SS
what is the best way to do it ? thanks for help .

Replies are listed 'Best First'.
Re: reading matrix and printing
by davido (Cardinal) on Feb 20, 2004 at 06:09 UTC
    Here's an ugly C-like solution that nevertheless works.

    use strict; use warnings; my @array; while ( my $line = <DATA> ) { chomp $line; push @array, [ split /\s+/, $line ]; } for ( my $column = 0; $column < @{$array[0]}; $column++ ) { for ( my $row = 0; $row < @array; $row++ ) { print $array[$row][$column], " "; } print "\n"; } __DATA__ 1 a x 2 b y 3 c z


    Dave

Re: reading matrix and printing
by jweed (Chaplain) on Feb 20, 2004 at 06:17 UTC
    You might want to check out the transpose feature of Math::Matrix. It may seem like overkill now, but when your matrices get large enough doing it manually is a pain.



    Code is (almost) always untested.
    http://www.justicepoetic.net/
Re: reading matrix and printing
by Anonymous Monk on Feb 20, 2004 at 05:18 UTC

    My first stab, thought up real fast, most likely not the best solution:

    use strict; use warnings; my (@one, @two, @three); while (<DATA>) { chomp; /([^ ]+) ([^ ]+) ([^ ]+)/; push @one, $1; push @two, $2; push @three, $3; } print join("\n", join(' ', @one), join(' ', @two), join(' ', @three)), + "\n"; __DATA__ 1 cow MM 2 cat DD 3 fly SS