Created
December 12, 2015 11:50
-
-
Save kuronekomichael/22d940aa19248371675d to your computer and use it in GitHub Desktop.
簡易的なテキストファイルパーサー
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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