You are on page 1of 18

Generation of a HASH OF ARRAYS

1. # reading from file


2. # flintstones: fred barney wilma dino
3. while ( <> ) {
4. next unless s/^(.*?):\s*//;
5. $HoA{$1} = [ split ];
6. }
7.
8. # reading from file; more temps
9. # flintstones: fred barney wilma dino
10. while ( $line = <> ) {
11. ($who, $rest) = split /:\s*/, $line, 2;
12. @fields = split ' ', $rest;
13. $HoA{$who} = [ @fields ];
14. }
15.
16. # calling a function that returns a list
17. for $group ( "simpsons", "jetsons", "flintstones" ) {
18. $HoA{$group} = [ get_family($group) ];
19. }
20.
21. # likewise, but using temps
22. for $group ( "simpsons", "jetsons", "flintstones" ) {
23. @members = get_family($group);
24. $HoA{$group} = [ @members ];
25. }
26.
27. # append new members to an existing family
28. push @{ $HoA{"flintstones"} }, "wilma", "betty";

Access and Printing of a HASH OF ARRAYS

1. # one element
2. $HoA{flintstones}[0] = "Fred";
3.
4. # another element
5. $HoA{simpsons}[1] =~ s/(\w)/\u$1/;
6.
7. # print the whole thing
8. foreach $family ( keys %HoA ) {
9. print "$family: @{ $HoA{$family} }\n"
10. }
11.
12. # print the whole thing with indices
13. foreach $family ( keys %HoA ) {
14. print "family: ";
15. foreach $i ( 0 .. $#{ $HoA{$family} } ) {
16. print " $i = $HoA{$family}[$i]";
17. }
18. print "\n";
19. }
20.
21. # print the whole thing sorted by number of members
22. foreach $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) {
23. print "$family: @{ $HoA{$family} }\n"
24. }
25.
26. # print the whole thing sorted by number of members and name
27. foreach $family ( sort {
28. @{$HoA{$b}} <=> @{$HoA{$a}}
29. ||
30. $a cmp $b
31. } keys %HoA )
32. {
33. print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n";
34. }

ARRAYS OF HASHES
Declaration of an ARRAY OF HASHES

1. @AoH = (
2. {
3. Lead => "fred",
4. Friend => "barney",
5. },
6. {
7. Lead => "george",
8. Wife => "jane",
9. Son => "elroy",
10. },
11. {
12. Lead => "homer",
13. Wife => "marge",
14. Son => "bart",
15. }
16. );

Generation of an ARRAY OF HASHES

1. # reading from file


2. # format: LEAD=fred FRIEND=barney
3. while ( <> ) {
4. $rec = {};
5. for $field ( split ) {
6. ($key, $value) = split /=/, $field;
7. $rec->{$key} = $value;
8. }
9. push @AoH, $rec;
10. }
11.
12.
13. # reading from file
14. # format: LEAD=fred FRIEND=barney
15. # no temp
16. while ( <> ) {
17. push @AoH, { split /[\s+=]/ };
18. }
19.
20. # calling a function that returns a key/value pair list, like
21. # "lead","fred","daughter","pebbles"
22. while ( %fields = getnextpairset() ) {
23. push @AoH, { %fields };
24. }
25.
26. # likewise, but using no temp vars
27. while (<>) {
28. push @AoH, { parsepairs($_) };
29. }
30.
31. # add key/value to an element
32. $AoH[0]{pet} = "dino";
33. $AoH[2]{pet} = "santa's little helper";

Access and Printing of an ARRAY OF HASHES

1. # one element
2. $AoH[0]{lead} = "fred";
3.
4. # another element
5. $AoH[1]{lead} =~ s/(\w)/\u$1/;
6.
7. # print the whole thing with refs
8. for $href ( @AoH ) {
9. print "{ ";
10. for $role ( keys %$href ) {
11. print "$role=$href->{$role} ";
12. }
13. print "}\n";
14. }
15.
16. # print the whole thing with indices
17. for $i ( 0 .. $#AoH ) {
18. print "$i is { ";
19. for $role ( keys %{ $AoH[$i] } ) {
20. print "$role=$AoH[$i]{$role} ";
21. }
22. print "}\n";
23. }
24.
25. # print the whole thing one at a time
26. for $i ( 0 .. $#AoH ) {
27. for $role ( keys %{ $AoH[$i] } ) {
28. print "elt $i $role is $AoH[$i]{$role}\n";
29. }
30. }

HASHES OF HASHES
Declaration of a HASH OF HASHES

1. %HoH = (
2. flintstones => {
3. lead => "fred",
4. pal => "barney",
5. },
6. jetsons => {
7. lead => "george",
8. wife => "jane",
9. "his boy" => "elroy",
10. },
11. simpsons => {
12. lead => "homer",
13. wife => "marge",
14. kid => "bart",
15. },
16. );

Generation of a HASH OF HASHES

1. # reading from file


2. # flintstones: lead=fred pal=barney wife=wilma pet=dino
3. while ( <> ) {
4. next unless s/^(.*?):\s*//;
5. $who = $1;
6. for $field ( split ) {
7. ($key, $value) = split /=/, $field;
8. $HoH{$who}{$key} = $value;
9. }
10.
11.
12. # reading from file; more temps
13. while ( <> ) {
14. next unless s/^(.*?):\s*//;
15. $who = $1;
16. $rec = {};
17. $HoH{$who} = $rec;
18. for $field ( split ) {
19. ($key, $value) = split /=/, $field;
20. $rec->{$key} = $value;
21. }
22. }
23.
24. # calling a function that returns a key,value hash
25. for $group ( "simpsons", "jetsons", "flintstones" ) {
26. $HoH{$group} = { get_family($group) };
27. }
28.
29. # likewise, but using temps
30. for $group ( "simpsons", "jetsons", "flintstones" ) {
31. %members = get_family($group);
32. $HoH{$group} = { %members };
33. }
34.
35. # append new members to an existing family
36. %new_folks = (
37. wife => "wilma",
38. pet => "dino",
39. );
40.
41. for $what (keys %new_folks) {
42. $HoH{flintstones}{$what} = $new_folks{$what};
43. }

Access and Printing of a HASH OF HASHES

1. # one element
2. $HoH{flintstones}{wife} = "wilma";
3.
4. # another element
5. $HoH{simpsons}{lead} =~ s/(\w)/\u$1/;
6.
7. # print the whole thing
8. foreach $family ( keys %HoH ) {
9. print "$family: { ";
10. for $role ( keys %{ $HoH{$family} } ) {
11. print "$role=$HoH{$family}{$role} ";
12. }
13. print "}\n";
14. }
15.
16. # print the whole thing somewhat sorted
17. foreach $family ( sort keys %HoH ) {
18. print "$family: { ";
19. for $role ( sort keys %{ $HoH{$family} } ) {
20. print "$role=$HoH{$family}{$role} ";
21. }
22. print "}\n";
23. }
24.
25.
26. # print the whole thing sorted by number of members
27. foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) {
28. print "$family: { ";
29. for $role ( sort keys %{ $HoH{$family} } ) {
30. print "$role=$HoH{$family}{$role} ";
31. }
32. print "}\n";
33. }
34.
35. # establish a sort order (rank) for each role
36. $i = 0;
37. for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
38.
39. # now print the whole thing sorted by number of members
40. foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) {
41. print "$family: { ";
42. # and print these according to rank order
43. for $role ( sort { $rank{$a} <=> $rank{$b} } keys %{ $HoH{$family} } ) {
44. print "$role=$HoH{$family}{$role} ";
45. }
46. print "}\n";
47. }

MORE ELABORATE RECORDS


Declaration of MORE ELABORATE RECORDS

Here's a sample showing how to create and use a record whose fields are of many different sorts:

1. $rec = {
2. TEXT => $string,
3. SEQUENCE => [ @old_values ],
4. LOOKUP => { %some_table },
5. THATCODE => \&some_function,
6. THISCODE => sub { $_[0] ** $_[1] },
7. HANDLE => \*STDOUT,
8. };
9.
10. print $rec->{TEXT};
11.
12. print $rec->{SEQUENCE}[0];
13. $last = pop @ { $rec->{SEQUENCE} };
14.
15. print $rec->{LOOKUP}{"key"};
16. ($first_k, $first_v) = each %{ $rec->{LOOKUP} };
17.
18. $answer = $rec->{THATCODE}->($arg);
19. $answer = $rec->{THISCODE}->($arg1, $arg2);
20.
21. # careful of extra block braces on fh ref
22. print { $rec->{HANDLE} } "a string\n";
23.
24. use FileHandle;
25. $rec->{HANDLE}->autoflush(1);
26. $rec->{HANDLE}->print(" a string\n");

Declaration of a HASH OF COMPLEX RECORDS

1. %TV = (
2. flintstones => {
3. series => "flintstones",
4. nights => [ qw(monday thursday friday) ],
5. members => [
6. { name => "fred", role => "lead", age => 36, },
7. { name => "wilma", role => "wife", age => 31, },
8. { name => "pebbles", role => "kid", age => 4, },
9. ],
10. },
11.
12. jetsons => {
13. series => "jetsons",
14. nights => [ qw(wednesday saturday) ],
15. members => [
16. { name => "george", role => "lead", age => 41, },
17. { name => "jane", role => "wife", age => 39, },
18. { name => "elroy", role => "kid", age => 9, },
19. ],
20. },
21.
22. simpsons => {
23. series => "simpsons",
24. nights => [ qw(monday) ],
25. members => [
26. { name => "homer", role => "lead", age => 34, },
27. { name => "marge", role => "wife", age => 37, },
28. { name => "bart", role => "kid", age => 11, },
29. ],
30. },
31. );

Generation of a HASH OF COMPLEX RECORDS

1. # reading from file


2. # this is most easily done by having the file itself be
3. # in the raw data format as shown above. perl is happy
4. # to parse complex data structures if declared as data, so
5. # sometimes it's easiest to do that
6.
7. # here's a piece by piece build up
8. $rec = {};
9. $rec->{series} = "flintstones";
10. $rec->{nights} = [ find_days() ];
11.
12. @members = ();
13. # assume this file in field=value syntax
14. while (<>) {
15. %fields = split /[\s=]+/;
16. push @members, { %fields };
17. }
18. $rec->{members} = [ @members ];
19.
20. # now remember the whole thing
21. $TV{ $rec->{series} } = $rec;
22.
23. ###########################################################
24. # now, you might want to make interesting extra fields that
25. # include pointers back into the same data structure so if
26. # change one piece, it changes everywhere, like for example
27. # if you wanted a {kids} field that was a reference
28. # to an array of the kids' records without having duplicate
29. # records and thus update problems.
30. ###########################################################
31. foreach $family (keys %TV) {
32. $rec = $TV{$family}; # temp pointer
33. @kids = ();
34. for $person ( @{ $rec->{members} } ) {
35. if ($person->{role} =~ /kid|son|daughter/) {
36. push @kids, $person;
37. }
38. }
39. # REMEMBER: $rec and $TV{$family} point to same data!!
40. $rec->{kids} = [ @kids ];
41. }
42.
43. # you copied the array, but the array itself contains pointers
44. # to uncopied objects. this means that if you make bart get
45. # older via
46.
47. $TV{simpsons}{kids}[0]{age}++;
48.
49. # then this would also change in
50. print $TV{simpsons}{members}[2]{age};
51.
52. # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
53. # both point to the same underlying anonymous hash table
54.
55. # print the whole thing
56. foreach $family ( keys %TV ) {
57. print "the $family";
58. print " is on during @{ $TV{$family}{nights} }\n";
59. print "its members are:\n";
60. for $who ( @{ $TV{$family}{members} } ) {
61. print " $who->{name} ($who->{role}), age $who->{age}\n";
62. }
63. print "it turns out that $TV{$family}{lead} has ";
64. print scalar ( @{ $TV{$family}{kids} } ), " kids named ";
65. print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } );
66. print "\n";
67. }

Database Ties

You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file. The first
problem is that all but GDBM and Berkeley DB have size limitations, but beyond that, you also
have problems with how references are to be represented on disk. One experimental module that
does partially attempt to address this need is the MLDBM module. Check your nearest CPAN site
as described in perlmodlib for source code to MLDBM.
SEE ALSO

perlref, perllol, perldata, perlobj


AUTHOR

Tom Christiansen <tchrist@perl.com>

Last update: Wed Oct 23 04:57:50 MET DST 1996


Page index

* NAME
* DESCRIPTION
* REFERENCES
* COMMON MISTAKES
* CAVEAT ON PRECEDENCE
* WHY YOU SHOULD ALWAYS use strict
* DEBUGGING
* CODE EXAMPLES
* ARRAYS OF ARRAYS
o Declaration of an ARRAY OF ARRAYS
o Generation of an ARRAY OF ARRAYS
o Access and Printing of an ARRAY OF ARRAYS
* HASHES OF ARRAYS
o Declaration of a HASH OF ARRAYS
o Generation of a HASH OF ARRAYS
o Access and Printing of a HASH OF ARRAYS
* ARRAYS OF HASHES
o Declaration of an ARRAY OF HASHES
o Generation of an ARRAY OF HASHES
o Access and Printing of an ARRAY OF HASHES
* HASHES OF HASHES
o Declaration of a HASH OF HASHES
o Generation of a HASH OF HASHES
o Access and Printing of a HASH OF HASHES
* MORE ELABORATE RECORDS
o Declaration of MORE ELABORATE RECORDS
o Declaration of a HASH OF COMPLEX RECORDS
o Generation of a HASH OF COMPLEX RECORDS
* Database Ties
* SEE ALSO
* AUTHOR

perldoc.perl.org - Official documentation for the Perl programming language

Contact details

Site maintained by Jon Allen (JJ)


See the project page for more details

Documentation maintained by the Perl 5 Porters


* Manual
o Overview
o Tutorials
o FAQs
o Changes
* Reference
o Language
o Functions
o Operators
o Variables
* Modules
o Modules
o Pragmas
o Utilities
* Misc
o License
o Internals
o Platforms
Anggi
annggi
jupri

You might also like