Little Code Little Code - 9 months ago 54
Perl Question

Adding quotes to a CSV using perl

I've got a CSV that looks as follows:


This is the desired file after transformation:


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 Source

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

#!/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";


cat input | perl