1

Say I have 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.

1 Answer 1

4

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: $!";
Sign up to request clarification or add additional context in comments.

1 Comment

Maybe have two filehandles open - one for input and one for output. That way you can read and process each line in turn and don't need that potentially quite large) @rows array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.