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

Hi everyone, I'm highly confused and therefore I am at your mercy to empart with some wisdom! I've got an array of arrays @out, which I need to print to a file as tsv. I had
for $row ( @out ) { print "@$row\n"; }
But I can't work out how to iterate through the embedded array to but the tab in? Heeeelp! Cheers, Tony

Replies are listed 'Best First'.
Re: Print AOA into tab sep values
by moritz (Cardinal) on Apr 14, 2008 at 11:07 UTC
    If you just want the tab chars:
    for my $row (@out){ local $" = "\t"; print "@$row\n"; }

    See perlvar for details.

    If you want to iterate over it:

    for my $row (@out){ for my $col (@$row){ # do something; } print "\n"; }
Re: Print AOA into tab sep values
by FunkyMonk (Bishop) on Apr 14, 2008 at 11:09 UTC
    One way:
    for $row ( @out ) { print join( "\t", @$row), "\n"; }

    Another way:

    $, = "\t"; # Output field separator for $row ( @out ) { print @$row, "\n"; }

    Update: moritz is right, $" is better than $, ($, leaves a TAB bebore NEWLINE)

      moritz is right, $" is better than $, ($, leaves a TAB bebore NEWLINE)

      Not at all. Just use $, in conjunction with $\.

      { local $, = "\t"; local $\ = "\n"; for my $row ( @out ) { print @$row; } }

      Of course, the join method much clearer.

        Joins are a little more expensive; If the number of elements in @out (num lines * num items per line) is in the millions, using $" is noticeably faster. If the expected size of the output will not be this huge, however, using join is much cleaner, as you pointed out.
Re: Print AOA into tab sep values
by Anonymous Monk on Apr 14, 2008 at 12:35 UTC
    Ladies and gents who answered, I love you all. Thank you a million