Name,Type,Age
Lily,Cat,4
Buster,Dog,5
Tweety,Bird,2
####
use strict;
use warnings;
use Text::CSV;
use subs qw(hlookup);
print "The animal in line 2 is ", hlookup("some_csv.csv", "Age", 2), " years old.\n";
print "The critter in line 4 is called ", hlookup("some_csv.csv", "Name", 4), ".\n";
sub hlookup {
my $csv_file = shift;
my $field_name = shift;
my $row_num = shift;
my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $fh, "<:encoding(utf8)", $csv_file or die "test.csv: $!";
my $field_num;
my $first_row = $csv->getline( $fh );
my @result;
for (my $idx = 0; $idx <= @$first_row; $idx++) {
if ($first_row->[$idx] eq $field_name) {
$field_num = $idx;
push @result, $first_row->[$field_num];
last;
}
}
die "Field name '$field_name' not found on the first row of $csv_file" if not defined $field_num;
while ( my $row = $csv->getline( $fh )) {
push @result, $row->[$field_num];
}
$csv->eof or $csv->error_diag();
close $fh;
return $result[$row_num - 1]; # -1 since array indexes are 0-based,
# and we count our lines 1-based
}
##
##
use strict;
use warnings;
use Text::CSV;
use subs qw(hlookup);
print "The animal in line 2 is ", hlookup("some_csv.csv", "Age", 2), " years old.\n";
print "The critter in line 4 is called ", hlookup("some_csv.csv", "Name", 4), ".\n";
sub hlookup {
my $csv_file = shift;
my $field_name = shift;
my $row_num = shift;
my $csv = Text::CSV->new ( { binary => 1 } ) # should set binary attribute.
or die "Cannot use CSV: ".Text::CSV->error_diag ();
open my $fh, "<:encoding(utf8)", $csv_file or die "test.csv: $!";
my $field_num;
my $first_row = $csv->getline( $fh );
$csv->column_names(@$first_row);
my $all = $csv->getline_hr_all($fh, $row_num - 2, 1);
# - 2 since array indexes are 0-based,
# and we count our lines 1-based,
# and because we've already read the first
# line.
return $all->[0]->{$field_name}
}
##
##
The animal in line 2 is 4 years old.
The critter in line 4 is called Tweety.