読者です 読者をやめる 読者になる 読者になる

Perl入学式 #2 復習問題 vote.pl

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper

my $info1 = { name => 'tarou', favorite_food => ['banana','banana','banana']};
my $info2 = { name => 'jirou', favorite_food => ['banana','mikan','kakuni']};
my $info3 = { name => 'saburo', favorite_food => ['banana','orange','aaa']};
my @array = ($info1,$info2,$info3);
my @array2;
# みんなの好きな食べ物を配列に突っ込んでる
for my $line ( @array){
        push(@array2,@{$line->{favorite_food}});
}

my %cnt;
foreach my $food (@array2){
        if($cnt{$food}) {
                $cnt{$food}=$cnt{$food}+1;
        } else {
                $cnt{$food}=1;
        }
}

#カウントした回数(値)をキーとともに出力
foreach my $key (sort(keys(%cnt))){
        print "$cnt{$key} $key\n";
}