Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

How do I create a CSV from a 2D array?

( #46529=categorized question: print w/ replies, xml ) Need Help??
Contributed by bari on Dec 14, 2000 at 04:30 UTC
Q&A  > arrays


Description:

I have an array-of-arrays, containing numbers and strings, and I want to represent it as Comma-Separated Values and Tab-Separated Values.

Answer: How do I create a CSV from a 2D array?
contributed by merlyn

Definitely start with Text::CSV or DBD::CSV.

Answer: How do I create a CSV from a 2D array?
contributed by bart

If you plan to print it to a file directly, and not quoting the individual fields (for a simple tab separated values table) I think using the special variables $, and $\ is the approach leaving the code most readable:

@headers = qw(one two three); @rows = ( ['yes', 'no', 'maybe'], ['alpha', 'beta', 'and all the rest'], ); { local($\, $,) = ("\n", "\t"); print @headers; print @$_ foreach @rows; }

It's more complex if you want a CSV file, where the field values can contain the delimiter, the quoting character, or a newline. The next code will only quote a field if necessary:

@headers = qw(one two three); @rows = ( ['yes', 'no', 'maybe'], ['17" monitor', 'a;b', "foo\nbar"], ); { local($\, $,) = ("\n", ";"); print map { my $s = $_; $s =~ s/([\n;])|"/ $1 || '""' /ge and $s = qq["$s"]; $s } @$_ foreach \@headers, @rows; }
Following the modern Microsoft preference, I've used semicolons for the delimiter; and I've doubled the literal quotes appearing in the field data.
Answer: How do I create a CSV from a 2D array?
contributed by jdporter

Try Text::CSV_XS by h. merijn brand, or Text::xSV by tilly.

Answer: How do I create a CSV from a 2D array?
contributed by ichimunki

As long as you are sure the list is two dimensional, this should work. First argument is the delimiter, second is the array. If you print the returned scalar to a filehandle, you will create a .csv file:
-------

my $write_this_to_file = delimit( ", ", @array ); sub delimit { my $delim = shift; my $delimited_file; foreach $row (@_) { $delimited_file .= join ($delim, @$row); $delimited_file .= "\n"; } return $delimited_file; }
Answer: How do I create a CSV from a 2D array?
contributed by Anonymous Monk

or, alternately:

sub delimit { my $delim = shift; return join('', map { join($delim, @$_) . "\n" } @_); }

Answer: How do I create a CSV from a 2D array?
contributed by fenonn

As long as @data is a 2D array this statement will store the data in CSV form in the scalar $temp so that it can be printed out to a file.

$temp = join "\n", map { $_ = join ",", @{$_} } @data;

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others about the Monastery: (15)
    As of 2014-09-19 12:41 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      How do you remember the number of days in each month?











      Results (138 votes), past polls