我感觉好像缺少了一些显而易见的东西,但是在文档中找不到任何答案。使用Perl对OOP还是陌生的,但是我正在使用Text :: CSV来解析CSV以供以后使用。
我将如何提取第一行并将值推入数组@headers?
这是我到目前为止的内容:
#!/usr/bin/perl
use warnings;
use diagnostics;
use strict;
use Fcntl ':flock';
use Text::CSV;
my $csv = Text::CSV->new({ sep_char => ',' });
my $file = "sample.csv";
my @headers; # Column names
open(my $data, '<:encoding(utf8)', $file) or die "Could not open '$file' $!\n";
while (my $line = <$data>) {
chomp $line;
if ($csv->parse($line)) {
my $r = 0; # Increment row counter
my $field_count = $csv->fields(); # Number of fields in row
# While data exists...
while (my $fields = $csv->getline( $data )) {
# Parse row into columns
print "Row ".$r.": \n";
# If row zero, process headers
if($r==0) {
# Add value to @columns array
push(@headers,$fields->[$c]);
} else {
# do stuff with records...
}
}
$r++
}
close $data;
您可能会想到有一种方法可以引用第一行中的现有字段。
例如,从文档中可以直接得出。
#!/usr/bin/perl
use strict;
use warnings;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new ({ binary => 1, eol => $/ });
my $file = 'o33.txt';
open my $io, "<", $file or die "$file: $!";
my $header = $csv->getline ($io);
print join("-", @$header), "\n\n";
while (my $row = $csv->getline ($io)) {
print join("-", @$row), "\n";
}
__END__
***contents of o33.txt
lastname,firstname,age,gender,phone
mcgee,bobby,27,M,555-555-5555
kincaid,marl,67,M,555-666-6666
hofhazards,duke,22,M,555-696-6969
印刷:
lastname-firstname-age-gender-phone
mcgee-bobby-27-M-555-555-5555
kincaid-marl-67-M-555-666-6666
hofhazards-duke-22-M-555-696-6969
更新:考虑到您的问题,可能是您想通过列名来处理数据。为此,您可能可以使用某些东西(也来自文档),例如:
$csv->column_names ($csv->getline ($io));
while (my $href = $csv->getline_hr ($io)) {
print "lastname is: ", $href->{lastname},
" and gender is: ", $href->{gender}, "\n"
}
注意:可以使用Text::CSV
代替Text::CSV_XS
,因为前者是后者的包装。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句