Perl Tutorial
Fundamentals
Input and Output
Control Flow
Arrays and Lists
Hash
Scalars
Strings
Object Oriented Programming in Perl
Subroutines
Regular Expressions
File Handling
Context Sensitivity
CGI Programming
Misc
Reading CSV (Comma-Separated Values) files is a common operation in many programming tasks. In Perl, there are a few ways to do this, but the most robust method is using the Text::CSV
module from CPAN. This tutorial will guide you on how to read a CSV file using Perl.
First, you'll need to install the Text::CSV
module. You can do this using cpan
:
cpan install Text::CSV
Here's a step-by-step guide on how to read a CSV file using the Text::CSV
module:
use strict; use warnings; use Text::CSV; # Create a new CSV parser instance my $csv = Text::CSV->new({ binary => 1, # Allow special characters auto_diag => 1, # Report irregularities }); # Open the CSV file open my $fh, '<', 'data.csv' or die "Could not open file: $!"; # Read the CSV file line-by-line while (my $row = $csv->getline($fh)) { # $row is now an array reference containing fields of the current row print "@$row\n"; } # Close the filehandle close $fh;
If your CSV has headers, you can map each row to a hash for easier access:
# Assuming data.csv has headers: name, age, email my $headers = $csv->getline($fh); # Get the headers $csv->column_names($headers); # Set column names while (my $row = $csv->getline_hr($fh)) { print "Name: $row->{name}, Age: $row->{age}, Email: $row->{email}\n"; }
Using auto_diag => 1
when creating the CSV object is helpful as it automatically reports issues with the CSV format. If you'd like to handle errors manually:
unless ($csv->parse($line)) { my $error = $csv->error_input; warn "Failed to parse line: $error"; next; # skip to next line or handle error as needed } my @fields = $csv->fields();
The Text::CSV
module provides a comprehensive and robust way to handle CSV files in Perl. By using it, you can ensure that your script can deal with a variety of CSV formats and edge cases. This tutorial covered reading a CSV file, but the module also supports creating and manipulating CSV content. It's a valuable tool for any Perl programmer dealing with data in CSV format.
CSV parsing in Perl example:
use Text::CSV; my $csv = Text::CSV->new({ binary => 1 }); open my $fh, '<', 'data.csv' or die "Could not open file: $!"; while (my $row = $csv->getline($fh)) { # Process each row print join(', ', @$row), "\n"; } close $fh;
Using Text::CSV module in Perl:
use Text::CSV; my $csv = Text::CSV->new({ binary => 1 });
Reading and parsing CSV data in Perl:
# ... (same as CSV parsing example)
Perl CSV reader script:
use Text::CSV; my $csv = Text::CSV->new({ binary => 1 }); open my $fh, '<', 'data.csv' or die "Could not open file: $!"; while (my $row = $csv->getline($fh)) { # Process each row print join(', ', @$row), "\n"; } close $fh;
CSV file processing with Perl:
# ... (same as Perl CSV reader script)
Handling headers in Perl CSV files:
use Text::CSV; my $csv = Text::CSV->new({ binary => 1, header => 1 }); open my $fh, '<', 'data.csv' or die "Could not open file: $!"; my $header = $csv->getline($fh); # Get the header while (my $row = $csv->getline($fh)) { # Access columns using header names print "Name: $row->{Name}, Age: $row->{Age}\n"; } close $fh;
Importing CSV data into Perl arrays or hashes:
# ... (same as Handling headers in Perl CSV files)
CSV file I/O with Perl:
use Text::CSV; my $csv = Text::CSV->new({ binary => 1, auto_diag => 1, eol => "\n" }); open my $fh, '>', 'output.csv' or die "Could not open file: $!"; my $header = ["Name", "Age"]; $csv->print($fh, $header); # Print header my $row = ["Alice", 25]; $csv->print($fh, $row); # Print data row close $fh;