PerlでCSVファイルの各項目の和を数えるサンプル

Perl サンプル

ファイル開く、HASH

#!c:/Perl/bin/perl.exe

print "処理開始\n";
print "\n\n";

%browser_target;

@targetfilename = ("agent_log.0","agent_log.1","agent_log.2","agent_log.3");

#ファイルの数だけ繰り返す
foreach my $item (@targetfilename) {
&sub_count($item);
}

#集計結果を表示
&sub_printhash();



sub sub_count {

my ($filename) = @_;

unless (open (IN, "< $filename")) {
print "Read open error ($file).\n";
exit (1);
}


#ファイルの内容をHASHにしてカウントアップさせる。
$nLoopCnt = 0;
while ( $line = ) {
$nLoopCnt += 1;
chomp($line);
#ブラウザの部分だけ抜き出す
my ($tmpdate,$target,$tmpip1) = split (/"/, $line);


$browser_target{$target} += 1;

}
close(IN);

print "ファイル ".$filename."読込み終了\n";
print "\n\n";

}


sub sub_printhash {

#HASHの内容の一覧を表示する

$nLoopCnt = 0;

foreach $key ( keys %browser_target ) {
print "種類:$key : 値:$browser_target{$key}", "\n";
$nLoopCnt += 1;
}

print "\n\n";

print "処理終了 ".$nLoopCnt."種類ありました";
print "\n\n";
}

exit(0);