Perl Hash of Arrays

From GM-RKB
Jump to navigation Jump to search

A Perl Hash of Arrays is a Perl Hash Data Structure that represents a Hash of Arrays Data Structure.



References

2001

  • (Cross, 2001) ⇒ David Cross. (2001). “Data Munging with Perl.” Manning Publications. ISBN:1930110006

2010

  • (Melli, 2010) ⇒ Gabor Melli. (2010). “Perl Hash of Arrays - Examples".
    • Composition of a hash of arrays
      Quotes are customarily omitted when keys are identifiers
 %HoA = (
    flintstones    ⇒ ["fred", "barney" ],
    jetsons        ⇒ ["george", "jane", "elroy" ],
    simpsons       ⇒ ["homer", "marge", "bart" ],
 );
Generation of a hash of arrays

Reading from file with the following format: flintstones: fred barney wilma dino

 while (<> ) {
    next unless s/^(.*?):\s*'' ;
    $HoA{$1} = [split ];
 }
  • Reading from file, with more temporary variables.
 while ($line = <> ) {
    ($who, $rest) = split /:\s*/, $line, 2;
    @fields = split ' ', $rest;
    $HoA{$who} = [@fields ];
 }
  • calling a function that returns an array
 for $group ("simpsons", "jetsons", "flintstones" ) {
    $HoA{$group} = [get_family($group) ];
 }
  • likewise, but using temporary variables
for $group ("simpsons", "jetsons", "flintstones" ) {
    @members = get_family($group);
    $HoA{$group} = [@members ];
}
  • append new members to an existing family
push @{ $HoA{flintstones} }, "wilma", "betty";
Access and printing of a hash of arrays
  • one element
$HoA{flintstones}[0] = "Fred";
  • another element
$HoA{simpsons}[1] =~ s/(\w)/\u$1/;
  • print the wHoAe thing
foreach $family (keys %HoA ) {
    print "$family: @{ $HoA{$family} }\n";;
}
  • print the wHoAe thing with indices
foreach $family (keys %HoA ) {
    print "$family: ";
    foreach $i (0 .. $#{ $HoA{$family} } ) {
        print " $i = $HoA{$family}[$i]";
    }
}
print "\n";
  • print the wHoAe thing sorted by number of members
foreach $family (sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
    print "$family: @{ $HoA{$family} }\n";
}
  • print the wHoAe thing sorted by number of members and name
foreach $family (sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
    print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n";
}