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.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why does split /,/ give the wrong number of fields for a CSV file?

    Answer

    It knows nothing about quotes, so a comma inside a quoted value starts a new field

    A real CSV field may hold a comma, a doubled quote or a newline, and only a parser that understands the quoting reads it as one value.

  2. What does Text::CSV do when Text::CSV_XS is installed?

    Answer

    It uses the faster compiled parser without a change to the code

    Text::CSV is the pure-Perl interface, and the XS module plugs in underneath at the same API.

  3. What does getline return at the end of a file?

    Answer

    An empty list, so the while loop ends

    The loop condition is a list assignment, and an empty list makes it false without a special end marker.

  4. What does binary => 1 do in a Text::CSV constructor?

    Answer

    It keeps the bytes of a field intact, newlines included

    The option turns off the text-mode handling of the record separator, which matters for embedded newlines and other encodings.

  5. What does auto_diag => 1 do?

    Answer

    It makes malformed input die with a message and a line number

    Without it a parse error leaves you to check the error status yourself, and the line number is the useful part.

  6. What must be set before getline_hr returns a hash for each row?

    Answer

    column_names

    The names tell the method which key each field gets, so the pairing is done for you.

  7. What does this program print? my $line = q{Ada,"wrote the first algorithm, in 1843"}; print scalar(split /,/, $line), "\n";

    Answer

    3

    The comma inside the quoted value is a separator to split, so it counts three fields where the CSV parser sees two.

  8. What does this program print? my $line = "a\tb\t10"; my @f = split /\t/, $line; print join("|", uc $f[0], $f[2]), "\n";

    Answer

    A|10

    The split gives the three tab-separated fields, and join puts the first and the third together with a pipe.

  9. What does this program print? my @header = ("region", "amount"); my @row = ("north", "1240.50"); my %rec; @rec{@header} = @row; print $rec{region}, " ", $rec{amount}, "\n";

    Answer

    north 1240.50

    The hash slice pairs each header name with the value in the same position of the row.

  10. What does this program print? my %total; for my $pair ([north => 10], [south => 5], [north => 2]) { $total{ $pair->[0] } += $pair->[1]; } for my $region (sort keys %total) { print "$region: $total{$region}\n"; }

    Answer

    north: 12 / south: 5

    The two north rows add into one entry, and sort puts north before south.

Article author: Arthur Isaev