2016年03月10日 16:30
%HoA = (
key01 => [ "val00", "val01" ],
key02 => [ "val10", "val11" ],
key03 => [ "val20", "val21" ],
);
# reading from file
# flintstones: fred barney wilma dino
while( <> ){
next unless s/^(.*?):\s*//;
$HoA{$1} = [ split ];
}
flintstones: fred barney wilma dino
rubbles: rubble betty bamm-bamm
others: slate arnold joe pearl
next unless s/^(.*?):\s*//;
$HoA{$1} = [ split ];
use Data::Dumper;
print Dumper \%HoA;
__END__
# Hash of Array
$VAR1 = {
'rubbles' => [
'rubble',
'betty',
'bamm-bamm'
],
'flintstones' => [
'fred',
'barney',
'wilma',
'dino'
],
'others' => [
'slate',
'arnold',
'joe',
'pearl'
]
};
# reading from file; more temps
while( my $line = <> ) {
# 空行をスキップ
next if $line =~ /\A\n\z/;
my ($who, $rest) = split /:\s*/, $line, 2;
my @fields = split ' ', $rest;
$HoA{$who} = [ @fields ];
}
# Calling a function that returns a list
foreach my $group ("simpsons", "jetsons", "flintstones" ) {
$HoA{$group} = [ get_family($group) ];
}
sub get_family {
my $group = shift;
if( $group eq 'flintstones' ){
qw/fred barney wilma dino/;
}elsif( $group eq 'jetsons' ){
qw/george jane judy elroy/;
}elsif( $group eq 'simpsons' ){
qw/homer marge bart lisa maggie/;
}
}
foreach my $group ("simpsons", "jetsons", "flintstones" ) {
$HoA{$group} = [ get_family($group) ];
}
use Data::Dumper;
print Dumper \%HoA;
__END__
# %HoA のデータ構造
$VAR1 = {
'flintstones' => [
'fred',
'barney',
'wilma',
'dino'
],
'simpsons' => [
'homer',
'marge',
'bart',
'lisa',
'maggie'
],
'jetsons' => [
'george',
'jane',
'judy',
'elroy'
]
};
# likewise, but using temps
foreach my $group ( "simpsons", "jetsons", "flintstones" ){
my @members = get_family($group);
$HoA{$group} = [ @members ];
}
# append new members to an existing family
push @{ $HoA{"flintstones"} }, "wilma", "betty";
# one element
${$HoA{flintstones}}[0] = "Fred";
$HoA{flintstones}->[0] = "Fred";
$HoA{flintstones}[0] = "Fred";
# another element
$HoA{simpsons}[1] =~ s/(\w)/\u$1/;
# print the whole thing
foreach my $family ( keys %HoA ){
print "family: @{ $HoA{$family} }\n";
}
# print the whole thing with indices
foreach my $family ( keys %HoA ){
print "family: ";
foreach my $i ( 0 .. $#{ $HoA{$family} } ){
print " $i = $HoA{$family}[$i]";
}
print "\n";
}
family: 0 = homer 1 = marge 2 = bart 3 = lisa 4 = maggie
family: 0 = fred 1 = barney 2 = wilma 3 = dino
family: 0 = george 1 = jane 2 = judy 3 = elroy
# print the whole thing sorted by number of memgers
foreach my $family ( sort { @{$HoA{$b}} @{$HoA{$a}} } keys %HoA ){
print "$family: @{ $HoA{$family} }\n";
}
simpsons: homer marge bart lisa maggie
jetsons: george jane
flintstones: fred
# print the whole thing sorted by number of members and name
foreach my $family ( sort {
# 要素数で 降順 sort
@{$HoA{$b}} <=> @{$HoA{$a}}
||
# または family name のアルファベットで 昇順 sort
$a cmp $b } keys %HoA )
{
print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n";
}
simpsons: bart, homer, lisa, maggie, marge
flintstones: barney, dino, fred, wilma
jetsons: elroy, george, jane, judy