Skip to content

Instantly share code, notes, and snippets.

@kuronekomichael
Created December 12, 2015 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuronekomichael/22d940aa19248371675d to your computer and use it in GitHub Desktop.
Save kuronekomichael/22d940aa19248371675d to your computer and use it in GitHub Desktop.
簡易的なテキストファイルパーサー
package ResourceParser;
use Exporter;
@ISA = qw(Exporter);
@EXPORT = qw(read_csv_file);
sub read_csv_file {
my $filename = shift or die 'no such csv filepath';
my $key_label = shift or die 'no such csv keyword';
my $results = {};
open FP, "<", $filename or die "Cannot open $filename:$!";
my @labels = map { s/\n$//;$_ } split(/,/, <FP>);
while (my $line = <FP>) {
chomp($line);
my $mactched_count = 0;
$mactched_count++ while ( $line =~ /"/g );
# もしダブルクォート("")が奇数なら、次の行もデータがあるとみなして連結する
while (($mactched_count % 2) == 1) {
my $newline = <FP>;
chomp($newline);
$mactched_count++ while ($newline =~ /"/g);
$line .= $newline;
}
my @packets = map { s/(^"|"$)//g;$_; } split(/,/, $line);
my $result = {};
foreach my $label(@labels) {
$result->{$label} = shift @packets;
}
$results->{$result->{$key_label}} = $result;
}
close FP;
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment