Little Code Little Code - 1 month ago 17
Perl Question

Adding quotes to a CSV using perl

I've got a CSV that looks as follows:

A,01,ALPHA
00,D,CHARLIE
E,F,02


This is the desired file after transformation:

"A",01,"ALPHA"
00,"D","CHARLIE"
"E","F",02


As you can see, the fields that are entirely numeric are left unquoted, whilst the alpha (or alphanumeric ones) are quoted.

What would be a sensible way to go about this in Perl ?

Already commented below, but I've tried stuff like

perl -pe 's/(\w+)/"$1"/g'


And that doesn't work because \w obviously picks up the numerics.

Answer

I recommend not reinventing the wheel, but rather to use an already existing module, as zdim recommends. Here is your example using Text::CSV_XS

test.pl

#!/usr/bin/env perl

use warnings;
use strict;

use Text::CSV_XS;
use Scalar::Util qw( looks_like_number );

my $csv = Text::CSV_XS->new();
while (my $row = $csv->getline(*STDIN)) {
    my @quoted_row = map { looks_like_number($_) ? $_ : '"'. $_ .'"' } @$row;
    print join(',',@quoted_row) . "\n";
}

Output

cat input | perl test.pl
"A",01,"ALPHA"
00,"D","CHARLIE"
"E","F",02