CSV and TSV processing

Why split is not enough

A comma-separated file looks like a list of fields per line, so the first instinct is split /,/. That works until a field contains a comma inside quotes, and real spreadsheets produce such fields constantly. Here is a small export:

printf 'name,note\nAda,"wrote the first algorithm, in 1843"\nGrace,"found the first real bug"\n' > export.csv

cat export.csv

name,note
Ada,"wrote the first algorithm, in 1843"
Grace,"found the first real bug"

Splitting that file by comma counts fields, not values: the second line comes out as three fields instead of two, because nothing in split knows about quotes.

perl -ne 'print scalar(split /,/), "\n"' export.csv

perl -ne 'print scalar(split /,/), "\n"' export.csv

2
3
2

Quotes can also hold a doubled quote or a newline, which means a record may span several physical lines.

Writing is just as tricky: a value with a comma, a quote or a newline has to be quoted and escaped, or the file becomes unreadable for every other tool.

Text::CSV

Text::CSV handles all of that. It uses the faster Text::CSV_XS automatically when it is installed, so you get a compiled parser without changing the code.

cpanm Text::CSV

printf 'region,amount\nnorth,1240.50\nsouth,980.00\nwest,3120.75\n' > sales.csv

use strict; use warnings; use Text::CSV; my $csv = Text::CSV->new({ binary => 1, auto_diag => 1, }); open my $fh, "<:encoding(UTF-8)", "sales.csv" or die "cannot read sales.csv: $!\n"; while (my $row = $csv->getline($fh)) { print scalar(@$row), " fields: @$row\n"; }

perl demo.pl

2 fields: region amount
2 fields: north 1240.50
2 fields: south 980.00
2 fields: west 3120.75

getline returns an array reference for one record or an empty list at end of file, so the while loop ends cleanly. binary => 1 keeps bytes intact, and auto_diag => 1 makes malformed input die with a line number instead of failing silently.

Working with headers

Most files start with a header row. Read it once, then turn every row into a hash so the rest of the program can use names instead of column numbers:

use Text::CSV; my $csv = Text::CSV->new({ binary => 1, auto_diag => 1 }); open my $fh, "<:encoding(UTF-8)", "sales.csv" or die "cannot read sales.csv: $!\n"; my $header = $csv->getline($fh) or die "sales.csv is empty\n"; my %total; while (my $row = $csv->getline($fh)) { my %rec; @rec{@$header} = @$row; $total{ $rec{region} } += $rec{amount}; } for my $region (sort keys %total) { printf "%-10s %10.2f\n", $region, $total{$region}; }

perl demo.pl

north 1240.50
south 980.00
west 3120.75

The hash slice @rec{@$header} = @$row pairs each column name with its value. If a row has fewer fields than the header, the missing values become undef and produce warnings, which is the signal you need to fix the source file.

Text::CSV also offers getline_hr, which does the pairing for you once you set column_names. That is shorter, but the explicit slice is easier to debug when a file has a stray blank line at the top.

Writing CSV and TSV

Set eol on the writer and use say, which combines the fields, quotes them when needed, and appends the line ending. The totals come from the program above, so the hash is repeated here:

use Text::CSV; my %total = (north => "1240.50", south => "980.00", west => "3120.75"); my $out = Text::CSV->new({ binary => 1, eol => "\n" }); open my $wfh, ">:encoding(UTF-8)", "clean.csv" or die "cannot write clean.csv: $!\n"; $out->say($wfh, ["region", "total"]); for my $region (sort keys %total) { $out->say($wfh, [$region, $total{$region}]); } print "wrote clean.csv\n";

perl demo.pl

wrote clean.csv

cat clean.csv

region,total
north,1240.50
south,980.00
west,3120.75

TSV is the same idea with a tab as separator. When the data is simple — no tab and no newline inside a field — split /\t/ and join "\t" are enough and need no module. This file has three columns, and the program uppercases the first one:

printf 'a\tb\t10\nc\td\t20\n' > sales.tsv

open my $fh, "<", "sales.tsv" or die "cannot read sales.tsv: $!\n"; while (my $line = <$fh>) { chomp $line; my @f = split /\t/, $line; print join("\t", uc $f[0], $f[1]), "\n"; }

perl demo.pl

A b
C d

If you need quoting in TSV, keep Text::CSV and pass sep_char => "\t". For anything else, check the module documentation rather than guessing: the options for quotes, escaping and embedded newlines are all described there.

Next: JSON with JSON::PP

Article author: Arthur Isaev