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

How to read csv files in Perl

Per has CSV library, that 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 a object using delimiter ({ sep_char => ‘,’ })

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

open a file using open funciton, read the content into $data variable.

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

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

use 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 below steps.

  • Open a file in write mode using 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 headernames
- Write header using  writeheader(), creates 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 below rows

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