LoginSignup
0
0

More than 3 years have passed since last update.

Text::CSVでCSVファイルをハッシュリファレンスとして読み込む

Posted at

メモというかスニペットとして。こんな感じかな。

  • $csv->getline($in)で1行目を読み込む。
  • 読み込んだ1行目をカラムラベル行とみなして、$csv->column_names(@$columns);でセットする。
  • $csv->getline_hr_all($in, 1);で引数指定した1行飛ばして2行目以降をハッシュリファレンスとして読み込む。

ログ出力にはLog::Minimaldebugf()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;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0