15.10. Process multi field csv file

Example 15-11. examples/applications/fields.csv

Name,ID,Input,Output
Big Venta,12,Left,Right
Small Elevator,7343124,Bottom,Top
Giant Ant,423235,Lower floor,Upper floor 

Example 15-12. examples/applications/process_fields.pl

#!/usr/bin/perl
use strict;
use warnings;

use Text::CSV_XS qw();
use Data::Dumper qw(Dumper);

my $filename = shift or die "Usage: $0 FILENAME\n";
open(my $fh, "<", $filename) or die "Could not open '$filename': $!";

my $csv = Text::CSV_XS->new;

my $key = "Name";

my $header = <$fh>;
chomp $header;
$csv->parse($header);
my @header = $csv->fields;

my %data;

while (my $line = <$fh>) {
    chomp $line;
    $csv->parse($line);
    my @cols = $csv->fields;
    my %h;
    @h{@header} = @cols;

    $data{$h{$key}} = \%h;
}

print Dumper \%data;



If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed