0

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'};

}
5
  • Can you give an example of a few lines from the CSV file? Commented Jun 27, 2014 at 15:44
  • The first few lines are junk Data. I need nothing up to row 8, where it contains the headers (IP, DNS, MAC...etc). Then below that it has the information for each host row by row. Commented Jun 27, 2014 at 15:48
  • Something along the lines of readline $io for 1 .. 7 before you read the header row? Commented Jun 27, 2014 at 15:52
  • I am new to text::csv. I am not honestly sure what I need to do to extract the header row and bind the data rows to it. Commented Jun 27, 2014 at 15:55
  • getline_all (gets all records) should be getline (gets a record), for starters. Commented Jun 27, 2014 at 15:57

2 Answers 2

1
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: $!";
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.