How to use the "split" command in Perl to read a file of comma separated values

By Alvin J. Alexander, devdaily.com

Problem

You have a file that contains columns of data, and each column is separated by a comma. The width of each column can vary, but the column data is guaranteed not to contain any columns itself, so it's safe to think of the comma as truly being a column separator. So, how do you read the data?

Solution

Okay, so what you're saying is that you have data that looks like this:

1, 2, 3, 4
22, 3.5,1777, 90120
1, 22, 333, 4444

and you want to be able to parse the data into four fields. This is easily done with the Perl split command. Here's a simple program that can be used to read a file named input.csv:

$file = 'input.csv';

open (F, $file) || die ("Could not open $file!");

while ($line = <F>)
{
  ($field1,$field2,$field3,$field4) = split ',', $line;
  print "$field1 : $field2 : $field3 : $field4";
}

close (F);

In this program the line that looks like this:

  ($field1,$field2,$field3,$field4) = split ',', $line;

is doing the work of splitting each line of data into four separate fields. Simply stated, this line says "Using the split command, take the current line of information, represented by $line, and split it into four fields, where each field is separated by a comma." Once you have the four fields of information as shown above, you can do whatever else you want to do with the data. In this case I'm just printing out the data, but obviously you'll want to do something else with your data.


devdaily logo