我正在尝试解析标题行位于第8行的文件。从第9行开始,n是我的数据。如何使用Text::CSV
执行此操作?我遇到了麻烦,我的代码如下:
my @cols = @{$csv->getline($io, 8)};
my $row = {};
$csv->bind_columns (\@{$row}{@cols});
while($csv->getline($io, 8)){
my $ip_addr = $row->{'IP'};
}
答案 0 :(得分: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: $!";
答案 1 :(得分:1)
你是否已经使用bind_columns死了?我想我已经看到了你想要做的事情,而且它在理论上非常具有创造性,但是如果您想要的是一种通过标题名称引用该列的方法,那么这样的事情如何:
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;
示例输入:
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
输出:
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