Read CSV file



examples/references/data.csv
fname,lname,phone
Boo,Bar,123
Foo,Baz,456
Moo,Zorg,789


We would like to read in that file and be able to access the fname of row 5
as  $data[3]{fname}

# the fname on line 5 is in index 3 because: 
# line 1 is the header
# line 2 is element 0 in the array
# ...
# line 5 is element 3 in the array


examples/references/read_csv_file.pl
#!/usr/bin/perl
use strict;
use warnings;

use Data::Dumper;

my $filename = shift 
    or die "Usage: $0 FILENAME ( examples/references/data.csv )\n";

my @data;
open my $fh, '<', $filename or die;

my $header = <$fh>;
chomp $header;
my @header = split /,/, $header;

while (my $line = <$fh>) {
    chomp $line;
    my %row;

    my @values = split /,/, $line;
    foreach my $i (0..@header-1) {
        my $field = $header[$i];
        $row{$field} = $values[$i];
    }
 
    # using hash slices:
    # @row{@header} = split /,/, $line;

    push @data, \%row;
}

print Dumper \@data;

$VAR1 = [
          {
            'lname' => 'Bar',
            'fname' => 'Boo',
            'phone' => '123'
          },
          {
            'lname' => 'Baz',
            'fname' => 'Foo',
            'phone' => '456'
          },
          {
            'lname' => 'Zorg',
            'fname' => 'Moo',
            'phone' => '789'
          }
        ];