Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Convert hash to CSV using Text::CSV::Slurp

by Plankton (Vicar)
on May 15, 2015 at 20:27 UTC ( #1126814=note: print w/replies, xml ) Need Help??


in reply to Convert hash to CSV using Text::CSV::Slurp

This seems to work for this particular instance of my problem:
my @cols; my @row; sub hash2csv { my $h = shift; my $p = shift || 'top'; foreach my $k ( keys %{$h} ) { if (ref $h->{$k} eq ref {}) { hash2csv( $h->{$k}, $k ); } else { if ( $p eq 'top' ) { push @cols, $k; } else { push @cols, "$p.$k"; } push @row, $h->{$k}; } } }
I wonder why I need Text::CSV::Slurp? Am I missing something? Will the above code break when passed other sorts of data?

Replies are listed 'Best First'.
Re^2: Convert hash to CSV using Text::CSV::Slurp
by Laurent_R (Canon) on May 16, 2015 at 12:14 UTC
    I wonder why I need Text::CSV::Slurp?
    According to its documentation, the create method of the Text::CSV::Slurp module can generate a CSV from an array of hashes. Here you have a hash of hashes, which is probably why you obtained scrambled output.

    Je suis Charlie.
Re^2: Convert hash to CSV using Text::CSV::Slurp
by Laurent_R (Canon) on May 16, 2015 at 11:59 UTC
    Hmm, I am not sure of what you do then with your @row and @cols arrays to populate your CSV.

    And what do you think will happen if you have other types of references (array refs, scalar refs, code refs, etc.) in your data structure? The program might probably not choke, but you'll see references (something like ARRAY(0x60005f6e0) in your output, instead of the actual data. Probably not what you want (although I am not entirely sure of what you want to obtain exactly).

    Je suis Charlie.
      print FH join( ',', @cols); print FH "\n"; print FH join( ',', @row); print FH "\n";
      And the developer of the API says I should always a expect HoH.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1126814]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2020-09-28 15:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (144 votes). Check out past polls.

    Notices?