开发者

Perl: Update a field in each line of a CSV file

开发者 https://www.devze.com 2023-01-23 07:03 出处:网络
Say I h开发者_如何学Pythonave a CSV file with thousands of lines similar to this one below: 1,fred,smith,\"11, erewhon avenue\",\"XYZ Company, 101 the road\",\"020 123456\",UK

Say I h开发者_如何学Pythonave a CSV file with thousands of lines similar to this one below:

1,fred,smith,"11, erewhon avenue","XYZ Company, 101 the road","020 123456",UK

I would like to use Perl to update the telephone number field only in the CSV file. I am thinking Text::CSV is the best way to go, but I'm not sure how to use it to update a field and write it back.


I must RTFM - I think this will do it:

use Text::CSV;

my @rows;
my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
             or die "Cannot use CSV: ".Text::CSV->error_diag ();

open my $fh, "<:encoding(utf8)", "test.csv" or die "test.csv: $!";
while ( my $row = $csv->getline( $fh ) ) {
   $row->[6] = get_new_tel_number();
   push @rows, $row;
}
$csv->eof or $csv->error_diag();
close $fh;

$csv->eol ("\r\n");

open $fh, ">:encoding(utf8)", "new.csv" or die "new.csv: $!";
$csv->print ($fh, $_) for @rows;
close $fh or die "new.csv: $!";
0

精彩评论

暂无评论...
验证码 换一张
取 消