メモというかスニペットとして。こんな感じかな。
-
$csv->getline($in)
で1行目を読み込む。 - 読み込んだ1行目をカラムラベル行とみなして、
$csv->column_names(@$columns);
でセットする。 -
$csv->getline_hr_all($in, 1);
で引数指定した1
行飛ばして2行目以降をハッシュリファレンスとして読み込む。
ログ出力にはLog::Minimal
のdebugf()
とwarnf()
を使用。
use 5.006;
use strict;
use warnings;
use utf8;
use Encode::Locale;
use Encode;
use Text::CSV_XS;
use Log::Minimal;
local $Log::Minimal::AUTODUMP = 1;
my $file = 'mydata.csv';
my @rows = &read_csv($file);
sub read_csv {
my $file = shift;
die "incorrect file specified: '$file'" unless (defined($file) && $file =~ /\S/ && -f $file);
my $csv = Text::CSV_XS->new ({ binary => 1 });
debugf("reading '%S'", $file);
open my $in, "<", $file || (warnf($!) && return());
my $columns = $csv->getline($in) || (warnf("Can't read columns line.") && return ());
scalar(@$columns) || (warnf("No columns in first line.") && return ());
$csv->column_names(@$columns);
my $rows = $csv->getline_hr_all($in, 1);
debugf("%d rows found.", scalar(@$rows));
close $in;
return @$rows;
}