eagles02
eagles02

Reputation: 65

Parsing CSV with Text::CSV

I am trying to parse a file where the header row is at row 8. From row 9-n is my data. How can I use Text::CSV to do this? I am having trouble, my code is below:

my @cols = @{$csv->getline($io, 8)};
my $row = {};
$csv->bind_columns (\@{$row}{@cols});


while($csv->getline($io, 8)){


    my $ip_addr = $row->{'IP'};

}

Upvotes: 0

Views: 442

Answers (2)

Hambone
Hambone

Reputation: 16397

Are you dead-set on using bind_columns? I think I see what you're trying to do, and it's notionally very creative, but if all you want is a way to reference the column by the header name, how about something like this:

use strict;
use warnings;

use Text::CSV;

my $csv = Text::CSV->new ( { binary => 1 } );
my (%header);

open my $io, "<", '/var/tmp/foo.csv' or die $!;
while (my $row = $csv->getline ($io)) {
  next unless $. > 7;
  my @fields = @$row; 

  unless (%header) {
    $header{$fields[$_]} = $_ for 0..$#fields;
    next;
  } 

  my $ip_addr = $fields[$header{'IP'}];
  print "$. => $ip_addr\n";
}
close $io;

Sample Input:

Test Data,,,
Trash,,,
Test Data,,,
Trash,,,
Beans,Joe,10.224.38.189,XYZ
Beans,Joe,10.224.38.190,XYZ
Beans,Joe,10.224.38.191,XYZ
Last Name,First Name,IP,Computer
Beans,Joe,10.224.38.192,XYZ
Beans,Joe,10.224.38.193,XYZ
Beans,Joe,10.224.38.194,XYZ
Beans,Joe,10.224.38.195,XYZ
Beans,Joe,10.224.38.196,XYZ
Beans,Joe,10.224.38.197,XYZ

Output:

9 => 10.224.38.192
10 => 10.224.38.193
11 => 10.224.38.194
12 => 10.224.38.195
13 => 10.224.38.196
14 => 10.224.38.197

Upvotes: 1

rajesh_pg
rajesh_pg

Reputation: 39

use Text::CSV;

my $csv = Text::CSV->new( ) or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $io, "test.csv" or die "test.csv: $!";
my $array_ref = $csv->getline_all($io,  8);
my $record = "";
foreach $record (@$array_ref) {
    print "$record->[0] \n";
}
close $io or die "test.csv: $!";

Upvotes: 1

Related Questions