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

Does anyone know of a quick and dirty way to print columns of comma delimited data? I've looked at the Text-CSV module but it doesn't quite do what I need. I have a data structure consisting of a hash of arrays, so my intent was to have each array represent a column of data.

I suppose I could just iterate through the keys in the hash and pull of an element of each array and write it to my csv file but that doesn't seem very effecient.

Any thoughts or suggestions?

Replies are listed 'Best First'.
Re: printing columns of data
by fmerges (Chaplain) on Sep 02, 2008 at 13:37 UTC

    Hi,

    Take a look at Text::Table.

    Regards,

    fmerges at irc.freenode.net
Re: printing columns of data
by Cristoforo (Curate) on Sep 02, 2008 at 13:42 UTC
Re: printing columns of data
by Anonymous Monk on Sep 02, 2008 at 13:01 UTC
    Here's my test code:
    use strict; use warnings; # use Data::Dumper; my %hash = (); my @array1 = qw(a b c d e); my @array2 = qw(1 2 3 4 5); push @{$hash{col1}}, @array1; push @{$hash{col2}}, @array2; # print Dumper(%hash); # Result should look like this: # col1,col2, # a,1 # b,2 # c,3 # d,4 # e,5

      If each row of output is built from data in multiple keys of the hash (per your test code), then I don't think you have any choice but to roll your own code that traverses everything and builds up the output.

      If you've got arbitrarily many keys in %hash, then you'll likely want something like this:

      use strict; use warnings; my %hash; $hash{col1} = [qw(a b c d e)]; $hash{col2} = [qw(1 2 3 4 5)]; $hash{col3} = [qw(q r s t u)]; # Change this so that the keys of %hash # show up in the order you want them, # in the output. my @keys = sort keys %hash; # Assumes every key of %hash is an # arrayref with the same number of # elements in it. Also note that # this code destroys %hash, as # it goes along. If you don't want # that, make a copy first. print join(",", @keys), "\n"; my $ref_key = $keys[0]; while (@{ $hash{$ref_key} }) { my @line; for my $key (@keys) { push @line, shift(@{ $hash{$key} }); } print join(",", @line), "\n"; }
        Here's a non-destructive version:
        use strict; use warnings; my %hash; $hash{col1} = [qw(a b c d e)]; $hash{col2} = [qw(1 2 3 4 5)]; $hash{col3} = [qw(q r s t u)]; # Change this so that the keys of %hash # show up in the order you want them, # in the output. my @keys = sort keys %hash; # Assumes every key of %hash is an # arrayref with the same number of # elements in it. print join(",", @keys), "\n"; my $ref_key = $keys[0]; my $count = @{ $hash{$ref_key} }; my $pos = 0; while ($pos < $count) { my @line; for my $key (@keys) { push @line, $hash{$key}[$pos]; } print join(",", @line), "\n"; ++$pos; }