Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: CSV manipulation with perl

by clueless newbie (Curate)
on Mar 09, 2009 at 15:43 UTC ( [id://749324]=note: print w/replies, xml ) Need Help??


in reply to CSV manipulation with perl

Ignoring the problem of parsing CSV, is this what you're looking for?
#!/perl/bin/perl use Smart::Comments; use strict; use warnings; my $_raa; my $i=0; while (<DATA>) { chomp; my @a=split(','); for my $j (0..$#a) { $_raa->[$j][$i]=$a[$j] }; $i++; }; ### $_raa __DATA__ 123,"text",66,"more text" 124,"text1",67,"more text1" 125,"text2",68,"more text2"
which yields
### $_raa: [ ### [ ### '123', ### '124', ### '125' ### ], ### [ ### '"text"', ### '"text1"', ### '"text2"' ### ], ### [ ### '66', ### '67', ### '68' ### ], ### [ ### '"more text"', ### '"more text1"', ### '"more text2"' ### ] ### ]

Replies are listed 'Best First'.
Re^2: CSV manipulation with perl
by Tanktalus (Canon) on Mar 09, 2009 at 22:23 UTC

    As a side note, I'd get rid of the $i and use what perl offers: push. (I'd also use an array rather than a reference to the array, but that's minor.)

    my @_raa; while (<DATA>) { chomp; my @a=split(','); # use Text::CSV_XS here. push @{$_raa[$_]}, $a[$_] for 0..$#a; };
    And then, if you do use Text::CSV_XS to extract the fields, use it to merge the fields back together, since the extraction will remove quotes and escapes, so you'll need to push it back with quotes and escapes (which Text::CSV_XS does for you automatically). The difference between my code and yours is that if some rows have more columns than others, we'll do different things. Yours will have some undef's in those places, while mine will silently ignore them, possibly shifting things around incorrectly. What to do in this scenario wasn't spec'd by the OP, so it's hard to tell which one is right.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (5)
As of 2024-04-25 14:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found