• Text::CSV modules for reading and writing CSV files in Perl with code examples

How to read CSV files in Perl

Per has CSV library, you need to read and write modules emp.csv file contains comma-separated values as given

1,john,2000,sales
2,Andrew,5000,finance
3,Mark,8000,hr
4,Rey,5000,marketing
5,Tan,4000,IT

Read CSV file line by line

First, Import Text::CSV module into the code using the use statement

use Text::CSV;

Next, create an object using delimiter ({ sep_char => ',' })

my $csv = Text::CSV->new({ sep_char => ',' });

Open a file using the open function, and read the content into $data variable.

open(my $data, '<', $file) or die "Unable not open '$file' $!\n";

Iterate file content lines using a while loop If the file is not found, It throws Unable not open 'emp11.csv' No such file or directory.

Use the while loop to read the line by line, and parse the line. Each line is a row in a CSV file with many columns.

while (my $line = <$data>)

Here is a complete example

use strict;
use warnings;

use Text::CSV;
my $csv = Text::CSV->new({ sep_char => ',' });

my $file = "emp.csv";
open(my $data, '<', $file) or die "Unable not open '$file' $!\n";
while (my $line = <$data>) {
  chomp $line;
  if ($csv->parse($line)) {
      my @row = $csv->fields();
      print "$row[0]- $row[1]- $row[2]\n";

  } else {
      warn "File line not able to parse: $line\n";
  }
}

Output:

1- john- 2000
2- Andrew- 5000
3- Mark- 8000
4- Rey- 5000
5- Tan- 4000

How to write to CSV file in Perl

To write to CSV file in Perl, Please follow the below steps.

  • Open a file in write mode using the open function
my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } )
               or die "Cannot use CSV: ".Text::CSV->error_diag ();
               ```

- Create a Writer using DictWriter with file and header names
- Write header using  writeheader(), creates the first line of header column names
- Add data using writeRow function with an object of key and values.

Here is a Python write CSV file example

```perl

import csv
my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } )
               or die "Cannot use CSV: ".Text::CSV->error_diag ();

open $fh, '>', "test.csv";



test.csv file created with the below rows

id,name
11,aaa
21,eee
31,ccc