February 2012
Intermediate to advanced
1184 pages
37h 17m
English
You can set the first element of a particular array as follows:
$HoA{flintstones}[0] = "Fred";To capitalize the second Simpson, apply a substitution to the appropriate array element:
$HoA{simpsons}[1] =~ s/(\w)/\u$1/;You can print all of the families by looping through the keys of the hash:
for $family ( keys %HoA ) {
say "$family: @{ $HoA{$family} }";
}With a little extra effort, you can add array indices as well:
for $family ( keys %HoA ) {
print "$family: ";
for $i ( 0 .. $#{ $HoA{$family} } ) {
print " $i = $HoA{$family}[$i]";
}
print "\n";
}Or sort the arrays by how many elements they have:
for $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
say "$family: @{ $HoA{$family} }"
}Or even sort the arrays by the number of elements and then order the elements ASCIIbetically (or, to be precise, utf8ically):
# Print the whole thing sorted by number of members and name.
for $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
say "$family: ", join(", " => sort @{ $HoA{$family} });
}If you have non-ASCII Unicode or even just punctuation of any sort in your family names, then sorting by codepoint order won’t produce an alphabetic sort. Instead, do this:
use Unicode::Collate;
my $sorter = Unicode::Collate–>new(); # normal alphabetic sort
say "$family: ",
join ", " => $sorter–>sort( @{ $HoA{$family} } );Read now
Unlock full access