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

Re: Search/Replace within fields of CSV

by Tux (Canon)
on May 08, 2015 at 18:55 UTC ( [id://1126146]=note: print w/replies, xml ) Need Help??


in reply to Search/Replace within fields of CSV

I'd say add a header line and use DBD::CSV. Of course you can do it with Text::CSV or Text::CSV_XS.

I'd use DBD::CSV if the dataset isn't too large (the whole set fits easily in memory).

I'd use Text::CSV_XS' csv function with on_in that lets you change fields on the fly.

$ cat test.pl #!/pro/bin/perl use 5.20.0; use warnings; use Text::CSV_XS "csv"; my %state = qw( 0H Ohio 0R Oregon C CONDENSED F Final ); csv (in => "test.csv", on_in => sub { $_[1][0] = $state{$_[1][0]} || $_[1][0]; $_[1][4] = $state{$_[1][4]} || $_[1][4]; }); $ cat test.csv C,003187995,0H047013N,20141212,0H,2050,EX,, C,013139784,0H0430000,20141110,0H,2014,EX,, C,153188023,0H0020000,20150105,0H,2015,BA,, C,173167740,MT007015G,20141202,0R,2015,BA,, $ perl test.pl CONDENSED,003187995,0H047013N,20141212,Ohio,2050,EX,, CONDENSED,013139784,0H0430000,20141110,Ohio,2014,EX,, CONDENSED,153188023,0H0020000,20150105,Ohio,2015,BA,, CONDENSED,173167740,MT007015G,20141202,Oregon,2015,BA,, $

update: As of version 1.17, you can also use filter (if you prefer that):

csv (in => "test.csv", filter => { 1 => sub { $_ = $state{$_} || $_ }, 5 => sub { $_ = $state{$_} || $_ }, });

Enjoy, Have FUN! H.Merijn

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-18 02:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found