Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Search/Replace within fields of CSV

by aaron_baugher (Curate)
on May 08, 2015 at 18:36 UTC ( [id://1126138]=note: print w/replies, xml ) Need Help??


in reply to Search/Replace within fields of CSV

The safest way to deal with CSV is with a module, and they're easy to use, so there's no reason not to. Let the module cleanly divide up the fields, make the changes you need, and write the results back out to a new file.

#!/usr/bin/env perl use 5.010; use strict; use warnings; use Text::CSV; my $ic = Text::CSV->new({sep_char => ','}) + or die Text::CSV->error_diag(); my $oc = Text::CSV->new({sep_char => ',', eol => $/ }) or die Text::CSV->error_diag(); open my $if, '<', 'infile' or die $!; open my $of, '>', 'outfile' or die $!; my %states = ( '0H' => 'OHIO', '0R' => 'OREGON', ); while( my $r = $ic->getline($if)){ $r->[0] = 'CONDENSED' if $r->[0] eq 'C'; $r->[0] = 'FINAL' if $r->[0] eq 'F'; $r->[4] = $states{$r->[4]} if $states{$r->[4]}; $oc->print($of, $r); } close $if; close $of;

Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.

Replies are listed 'Best First'.
Re^2: Search/Replace within fields of CSV
by johnmck (Initiate) on May 08, 2015 at 18:41 UTC
    Thanks very much, Aaron. I was thinking about Text::CSV but I wasn't sure if there was a more practical way to do it. Your code really helps. Thank you.

Log In?
Username:
Password:

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

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

    No recent polls found