.rn '' }` ''' $RCSfile$$Revision$$Date$ ''' ''' $Log$ ''' .de Sh .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp .if t .sp .5v .if n .sp .. .de Ip .br .ie \\n(.$>=3 .ne \\$3 .el .ne 3 .IP "\\$1" \\$2 .. .de Vb .ft CW .nf .ne \\$1 .. .de Ve .ft R .fi .. ''' ''' ''' Set up \*(-- to give an unbreakable dash; ''' string Tr holds user defined translation string. ''' Bell System Logo is used as a dummy character. ''' .tr \(*W-|\(bv\*(Tr .ie n \{\ .ds -- \(*W- .ds PI pi .if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch .if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch .ds L" "" .ds R" "" ''' \*(M", \*(S", \*(N" and \*(T" are the equivalent of ''' \*(L" and \*(R", except that they are used on ".xx" lines, ''' such as .IP and .SH, which do another additional levels of ''' double-quote interpretation .ds M" """ .ds S" """ .ds N" """"" .ds T" """"" .ds L' ' .ds R' ' .ds M' ' .ds S' ' .ds N' ' .ds T' ' 'br\} .el\{\ .ds -- \(em\| .tr \*(Tr .ds L" `` .ds R" '' .ds M" `` .ds S" '' .ds N" `` .ds T" '' .ds L' ` .ds R' ' .ds M' ` .ds S' ' .ds N' ` .ds T' ' .ds PI \(*p 'br\} .\" If the F register is turned on, we'll generate .\" index entries out stderr for the following things: .\" TH Title .\" SH Header .\" Sh Subsection .\" Ip Item .\" X<> Xref (embedded .\" Of course, you have to process the output yourself .\" in some meaninful fashion. .if \nF \{ .de IX .tm Index:\\$1\t\\n%\t"\\$2" .. .nr % 0 .rr F .\} .TH PERLDSC 1 "perl 5.005, patch 03" "5/Aug/1999" "Perl Programmers Reference Guide" .UC .if n .hy 0 .if n .na .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .de CQ \" put $1 in typewriter font .ft CW 'if n "\c 'if t \\&\\$1\c 'if n \\&\\$1\c 'if n \&" \\&\\$2 \\$3 \\$4 \\$5 \\$6 \\$7 '.ft R .. .\" @(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2 . \" AM - accent mark definitions .bd B 3 . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds ? ? . ds ! ! . ds / . ds q .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds ? \s-2c\h'-\w'c'u*7/10'\u\h'\*(#H'\zi\d\s+2\h'\w'c'u*8/10' . ds ! \s-2\(or\s+2\h'-\w'\(or'u'\v'-.8m'.\v'.8m' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' . ds q o\h'-\w'o'u*8/10'\s-4\v'.4m'\z\(*i\v'-.4m'\s+4\h'\w'o'u*8/10' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds v \\k:\h'-(\\n(.wu*9/10-\*(#H)'\v'-\*(#V'\*(#[\s-4v\s0\v'\*(#V'\h'|\\n:u'\*(#] .ds _ \\k:\h'-(\\n(.wu*9/10-\*(#H+(\*(#F*2/3))'\v'-.4m'\z\(hy\v'.4m'\h'|\\n:u' .ds . \\k:\h'-(\\n(.wu*8/10)'\v'\*(#V*4/10'\z.\v'-\*(#V*4/10'\h'|\\n:u' .ds 3 \*(#[\v'.2m'\s-2\&3\s0\v'-.2m'\*(#] .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E .ds oe o\h'-(\w'o'u*4/10)'e .ds Oe O\h'-(\w'O'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds v \h'-1'\o'\(aa\(ga' . ds _ \h'-1'^ . ds . \h'-1'. . ds 3 3 . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE . ds oe oe . ds Oe OE .\} .rm #[ #] #H #V #F C .SH "NAME" perldsc \- Perl Data Structures Cookbook .SH "DESCRIPTION" The single feature most sorely lacking in the Perl programming language prior to its 5.0 release was complex data structures. Even without direct language support, some valiant programmers did manage to emulate them, but it was hard work and not for the faint of heart. You could occasionally get away with the \f(CW$m{$LoL,$b}\fR notation borrowed from \fIawk\fR in which the keys are actually more like a single concatenated string \f(CW"$LoL$b"\fR, but traversal and sorting were difficult. More desperate programmers even hacked Perl's internal symbol table directly, a strategy that proved hard to develop and maintain\*(--to put it mildly. .PP The 5.0 release of Perl let us have complex data structures. You may now write something like this and all of a sudden, you'd have a array with three dimensions! .PP .Vb 8 \& for $x (1 .. 10) { \& for $y (1 .. 10) { \& for $z (1 .. 10) { \& $LoL[$x][$y][$z] = \& $x ** $y + $z; \& } \& } \& } .Ve Alas, however simple this may appear, underneath it's a much more elaborate construct than meets the eye! .PP How do you print it out? Why can't you say just \f(CWprint @LoL\fR? How do you sort it? How can you pass it to a function or get one of these back from a function? Is is an object? Can you save it to disk to read back later? How do you access whole rows or columns of that matrix? Do all the values have to be numeric? .PP As you see, it's quite easy to become confused. While some small portion of the blame for this can be attributed to the reference-based implementation, it's really more due to a lack of existing documentation with examples designed for the beginner. .PP This document is meant to be a detailed but understandable treatment of the many different sorts of data structures you might want to develop. It should also serve as a cookbook of examples. That way, when you need to create one of these complex data structures, you can just pinch, pilfer, or purloin a drop-in example from here. .PP Let's look at each of these possible constructs in detail. There are separate sections on each of the following: .Ip "\(bu arrays of arrays" 5 .Ip "\(bu hashes of arrays" 5 .Ip "\(bu arrays of hashes" 5 .Ip "\(bu hashes of hashes" 5 .Ip "\(bu more elaborate constructs" 5 .PP But for now, let's look at general issues common to all these types of data structures. .SH "REFERENCES" The most important thing to understand about all data structures in Perl -- including multidimensional arrays\*(--is that even though they might appear otherwise, Perl \f(CW@ARRAY\fRs and \f(CW%HASH\fRes are all internally one-dimensional. They can hold only scalar values (meaning a string, number, or a reference). They cannot directly contain other arrays or hashes, but instead contain \fIreferences\fR to other arrays or hashes. .PP You can't use a reference to a array or hash in quite the same way that you would a real array or hash. For C or \*(C+ programmers unused to distinguishing between arrays and pointers to the same, this can be confusing. If so, just think of it as the difference between a structure and a pointer to a structure. .PP You can (and should) read more about references in the \fIperlref\fR\|(1) man page. Briefly, references are rather like pointers that know what they point to. (Objects are also a kind of reference, but we won't be needing them right away\*(--if ever.) This means that when you have something which looks to you like an access to a two-or-more-dimensional array and/or hash, what's really going on is that the base type is merely a one-dimensional entity that contains references to the next level. It's just that you can \fIuse\fR it as though it were a two-dimensional one. This is actually the way almost all C multidimensional arrays work as well. .PP .Vb 4 \& $list[7][12] # array of arrays \& $list[7]{string} # array of hashes \& $hash{string}[7] # hash of arrays \& $hash{string}{'another string'} # hash of hashes .Ve Now, because the top level contains only references, if you try to print out your array in with a simple \fIprint()\fR function, you'll get something that doesn't look very nice, like this: .PP .Vb 5 \& @LoL = ( [2, 3], [4, 5, 7], [0] ); \& print $LoL[1][2]; \& 7 \& print @LoL; \& ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0) .Ve That's because Perl doesn't (ever) implicitly dereference your variables. If you want to get at the thing a reference is referring to, then you have to do this yourself using either prefix typing indicators, like \f(CW${$blah}\fR, \f(CW@{$blah}\fR, \f(CW@{$blah[$i]}\fR, or else postfix pointer arrows, like \f(CW$a->[3]\fR, \f(CW$h->{fred}\fR, or even \f(CW$ob->method()->[3]\fR. .SH "COMMON MISTAKES" The two most common mistakes made in constructing something like an array of arrays is either accidentally counting the number of elements or else taking a reference to the same memory location repeatedly. Here's the case where you just get the count instead of a nested array: .PP .Vb 4 \& for $i (1..10) { \& @list = somefunc($i); \& $LoL[$i] = @list; # WRONG! \& } .Ve That's just the simple case of assigning a list to a scalar and getting its element count. If that's what you really and truly want, then you might do well to consider being a tad more explicit about it, like this: .PP .Vb 4 \& for $i (1..10) { \& @list = somefunc($i); \& $counts[$i] = scalar @list; \& } .Ve Here's the case of taking a reference to the same memory location again and again: .PP .Vb 4 \& for $i (1..10) { \& @list = somefunc($i); \& $LoL[$i] = \e@list; # WRONG! \& } .Ve So, what's the big problem with that? It looks right, doesn't it? After all, I just told you that you need an array of references, so by golly, you've made me one! .PP Unfortunately, while this is true, it's still broken. All the references in \f(CW@LoL\fR refer to the \fIvery same place\fR, and they will therefore all hold whatever was last in \f(CW@list\fR! It's similar to the problem demonstrated in the following C program: .PP .Vb 5 \& #include \& main() { \& struct passwd *getpwnam(), *rp, *dp; \& rp = getpwnam("root"); \& dp = getpwnam("daemon"); .Ve .Vb 3 \& printf("daemon name is %s\enroot name is %s\en", \& dp->pw_name, rp->pw_name); \& } .Ve Which will print .PP .Vb 2 \& daemon name is daemon \& root name is daemon .Ve The problem is that both \f(CWrp\fR and \f(CWdp\fR are pointers to the same location in memory! In C, you'd have to remember to \fImalloc()\fR yourself some new memory. In Perl, you'll want to use the array constructor \f(CW[]\fR or the hash constructor \f(CW{}\fR instead. Here's the right way to do the preceding broken code fragments: .PP .Vb 4 \& for $i (1..10) { \& @list = somefunc($i); \& $LoL[$i] = [ @list ]; \& } .Ve The square brackets make a reference to a new array with a \fIcopy\fR of what's in \f(CW@list\fR at the time of the assignment. This is what you want. .PP Note that this will produce something similar, but it's much harder to read: .PP .Vb 4 \& for $i (1..10) { \& @list = 0 .. $i; \& @{$LoL[$i]} = @list; \& } .Ve Is it the same? Well, maybe so\*(--and maybe not. The subtle difference is that when you assign something in square brackets, you know for sure it's always a brand new reference with a new \fIcopy\fR of the data. Something else could be going on in this new case with the \f(CW@{$LoL[$i]}}\fR dereference on the left-hand-side of the assignment. It all depends on whether \f(CW$LoL[$i]\fR had been undefined to start with, or whether it already contained a reference. If you had already populated \f(CW@LoL\fR with references, as in .PP .Vb 1 \& $LoL[3] = \e@another_list; .Ve Then the assignment with the indirection on the left-hand-side would use the existing reference that was already there: .PP .Vb 1 \& @{$LoL[3]} = @list; .Ve Of course, this \fIwould\fR have the \*(L"interesting\*(R" effect of clobbering \f(CW@another_list\fR. (Have you ever noticed how when a programmer says something is \*(L"interesting\*(R", that rather than meaning \*(L"intriguing\*(R", they're disturbingly more apt to mean that it's \*(L"annoying\*(R", \*(L"difficult\*(R", or both? :\-) .PP So just remember always to use the array or hash constructors with \f(CW[]\fR or \f(CW{}\fR, and you'll be fine, although it's not always optimally efficient. .PP Surprisingly, the following dangerous-looking construct will actually work out fine: .PP .Vb 4 \& for $i (1..10) { \& my @list = somefunc($i); \& $LoL[$i] = \e@list; \& } .Ve That's because \fImy()\fR is more of a run-time statement than it is a compile-time declaration \fIper se\fR. This means that the \fImy()\fR variable is remade afresh each time through the loop. So even though it \fIlooks\fR as though you stored the same variable reference each time, you actually did not! This is a subtle distinction that can produce more efficient code at the risk of misleading all but the most experienced of programmers. So I usually advise against teaching it to beginners. In fact, except for passing arguments to functions, I seldom like to see the gimme-a-reference operator (backslash) used much at all in code. Instead, I advise beginners that they (and most of the rest of us) should try to use the much more easily understood constructors \f(CW[]\fR and \f(CW{}\fR instead of relying upon lexical (or dynamic) scoping and hidden reference-counting to do the right thing behind the scenes. .PP In summary: .PP .Vb 3 \& $LoL[$i] = [ @list ]; # usually best \& $LoL[$i] = \e@list; # perilous; just how my() was that list? \& @{ $LoL[$i] } = @list; # way too tricky for most programmers .Ve .SH "CAVEAT ON PRECEDENCE" Speaking of things like \f(CW@{$LoL[$i]}\fR, the following are actually the same thing: .PP .Vb 2 \& $listref->[2][2] # clear \& $$listref[2][2] # confusing .Ve That's because Perl's precedence rules on its five prefix dereferencers (which look like someone swearing: \f(CW$ @ * % &\fR) make them bind more tightly than the postfix subscripting brackets or braces! This will no doubt come as a great shock to the C or \*(C+ programmer, who is quite accustomed to using \f(CW*a[i]\fR to mean what's pointed to by the \fIi'th\fR element of \f(CWa\fR. That is, they first take the subscript, and only then dereference the thing at that subscript. That's fine in C, but this isn't C. .PP The seemingly equivalent construct in Perl, \f(CW$$listref[$i]\fR first does the deref of \f(CW$listref\fR, making it take \f(CW$listref\fR as a reference to an array, and then dereference that, and finally tell you the \fIi'th\fR value of the array pointed to by \f(CW$LoL\fR. If you wanted the C notion, you'd have to write \f(CW${$LoL[$i]}\fR to force the \f(CW$LoL[$i]\fR to get evaluated first before the leading \f(CW$\fR dereferencer. .SH "WHY YOU SHOULD ALWAYS \f(CWuse strict\fR" If this is starting to sound scarier than it's worth, relax. Perl has some features to help you avoid its most common pitfalls. The best way to avoid getting confused is to start every program like this: .PP .Vb 2 \& #!/usr/bin/perl -w \& use strict; .Ve This way, you'll be forced to declare all your variables with \fImy()\fR and also disallow accidental \*(L"symbolic dereferencing\*(R". Therefore if you'd done this: .PP .Vb 5 \& my $listref = [ \& [ "fred", "barney", "pebbles", "bambam", "dino", ], \& [ "homer", "bart", "marge", "maggie", ], \& [ "george", "jane", "elroy", "judy", ], \& ]; .Ve .Vb 1 \& print $listref[2][2]; .Ve The compiler would immediately flag that as an error \fIat compile time\fR, because you were accidentally accessing \f(CW@listref\fR, an undeclared variable, and it would thereby remind you to write instead: .PP .Vb 1 \& print $listref->[2][2] .Ve .SH "DEBUGGING" Before version 5.002, the standard Perl debugger didn't do a very nice job of printing out complex data structures. With 5.002 or above, the debugger includes several new features, including command line editing as well as the \f(CWx\fR command to dump out complex data structures. For example, given the assignment to \f(CW$LoL\fR above, here's the debugger output: .PP .Vb 18 \& DB<1> x $LoL \& $LoL = ARRAY(0x13b5a0) \& 0 ARRAY(0x1f0a24) \& 0 'fred' \& 1 'barney' \& 2 'pebbles' \& 3 'bambam' \& 4 'dino' \& 1 ARRAY(0x13b558) \& 0 'homer' \& 1 'bart' \& 2 'marge' \& 3 'maggie' \& 2 ARRAY(0x13b540) \& 0 'george' \& 1 'jane' \& 2 'elroy' \& 3 'judy' .Ve .SH "CODE EXAMPLES" Presented with little comment (these will get their own manpages someday) here are short code examples illustrating access of various types of data structures. .SH "LISTS OF LISTS" .Sh "Declaration of a \s-1LIST\s0 \s-1OF\s0 \s-1LISTS\s0" .PP .Vb 5 \& @LoL = ( \& [ "fred", "barney" ], \& [ "george", "jane", "elroy" ], \& [ "homer", "marge", "bart" ], \& ); .Ve .Sh "Generation of a \s-1LIST\s0 \s-1OF\s0 \s-1LISTS\s0" .PP .Vb 4 \& # reading from file \& while ( <> ) { \& push @LoL, [ split ]; \& } .Ve .Vb 4 \& # calling a function \& for $i ( 1 .. 10 ) { \& $LoL[$i] = [ somefunc($i) ]; \& } .Ve .Vb 5 \& # using temp vars \& for $i ( 1 .. 10 ) { \& @tmp = somefunc($i); \& $LoL[$i] = [ @tmp ]; \& } .Ve .Vb 2 \& # add to an existing row \& push @{ $LoL[0] }, "wilma", "betty"; .Ve .Sh "Access and Printing of a \s-1LIST\s0 \s-1OF\s0 \s-1LISTS\s0" .PP .Vb 2 \& # one element \& $LoL[0][0] = "Fred"; .Ve .Vb 2 \& # another element \& $LoL[1][1] =~ s/(\ew)/\eu$1/; .Ve .Vb 4 \& # print the whole thing with refs \& for $aref ( @LoL ) { \& print "\et [ @$aref ],\en"; \& } .Ve .Vb 4 \& # print the whole thing with indices \& for $i ( 0 .. $#LoL ) { \& print "\et [ @{$LoL[$i]} ],\en"; \& } .Ve .Vb 6 \& # print the whole thing one at a time \& for $i ( 0 .. $#LoL ) { \& for $j ( 0 .. $#{ $LoL[$i] } ) { \& print "elt $i $j is $LoL[$i][$j]\en"; \& } \& } .Ve .SH "HASHES OF LISTS" .Sh "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1LISTS\s0" .PP .Vb 5 \& %HoL = ( \& flintstones => [ "fred", "barney" ], \& jetsons => [ "george", "jane", "elroy" ], \& simpsons => [ "homer", "marge", "bart" ], \& ); .Ve .Sh "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1LISTS\s0" .PP .Vb 6 \& # reading from file \& # flintstones: fred barney wilma dino \& while ( <> ) { \& next unless s/^(.*?):\es*//; \& $HoL{$1} = [ split ]; \& } .Ve .Vb 7 \& # reading from file; more temps \& # flintstones: fred barney wilma dino \& while ( $line = <> ) { \& ($who, $rest) = split /:\es*/, $line, 2; \& @fields = split ' ', $rest; \& $HoL{$who} = [ @fields ]; \& } .Ve .Vb 4 \& # calling a function that returns a list \& for $group ( "simpsons", "jetsons", "flintstones" ) { \& $HoL{$group} = [ get_family($group) ]; \& } .Ve .Vb 5 \& # likewise, but using temps \& for $group ( "simpsons", "jetsons", "flintstones" ) { \& @members = get_family($group); \& $HoL{$group} = [ @members ]; \& } .Ve .Vb 2 \& # append new members to an existing family \& push @{ $HoL{"flintstones"} }, "wilma", "betty"; .Ve .Sh "Access and Printing of a \s-1HASH\s0 \s-1OF\s0 \s-1LISTS\s0" .PP .Vb 2 \& # one element \& $HoL{flintstones}[0] = "Fred"; .Ve .Vb 2 \& # another element \& $HoL{simpsons}[1] =~ s/(\ew)/\eu$1/; .Ve .Vb 4 \& # print the whole thing \& foreach $family ( keys %HoL ) { \& print "$family: @{ $HoL{$family} }\en" \& } .Ve .Vb 8 \& # print the whole thing with indices \& foreach $family ( keys %HoL ) { \& print "family: "; \& foreach $i ( 0 .. $#{ $HoL{$family} } ) { \& print " $i = $HoL{$family}[$i]"; \& } \& print "\en"; \& } .Ve .Vb 4 \& # print the whole thing sorted by number of members \& foreach $family ( sort { @{$HoL{$b}} <=> @{$HoL{$a}} } keys %HoL ) { \& print "$family: @{ $HoL{$family} }\en" \& } .Ve .Vb 9 \& # print the whole thing sorted by number of members and name \& foreach $family ( sort { \& @{$HoL{$b}} <=> @{$HoL{$a}} \& || \& $a cmp $b \& } keys %HoL ) \& { \& print "$family: ", join(", ", sort @{ $HoL{$family} }), "\en"; \& } .Ve .SH "LISTS OF HASHES" .Sh "Declaration of a \s-1LIST\s0 \s-1OF\s0 \s-1HASHES\s0" .PP .Vb 16 \& @LoH = ( \& { \& Lead => "fred", \& Friend => "barney", \& }, \& { \& Lead => "george", \& Wife => "jane", \& Son => "elroy", \& }, \& { \& Lead => "homer", \& Wife => "marge", \& Son => "bart", \& } \& ); .Ve .Sh "Generation of a \s-1LIST\s0 \s-1OF\s0 \s-1HASHES\s0" .PP .Vb 10 \& # reading from file \& # format: LEAD=fred FRIEND=barney \& while ( <> ) { \& $rec = {}; \& for $field ( split ) { \& ($key, $value) = split /=/, $field; \& $rec->{$key} = $value; \& } \& push @LoH, $rec; \& } .Ve .Vb 6 \& # reading from file \& # format: LEAD=fred FRIEND=barney \& # no temp \& while ( <> ) { \& push @LoH, { split /[\es+=]/ }; \& } .Ve .Vb 5 \& # calling a function that returns a key,value list, like \& # "lead","fred","daughter","pebbles" \& while ( %fields = getnextpairset() ) { \& push @LoH, { %fields }; \& } .Ve .Vb 4 \& # likewise, but using no temp vars \& while (<>) { \& push @LoH, { parsepairs($_) }; \& } .Ve .Vb 3 \& # add key/value to an element \& $LoH[0]{pet} = "dino"; \& $LoH[2]{pet} = "santa's little helper"; .Ve .Sh "Access and Printing of a \s-1LIST\s0 \s-1OF\s0 \s-1HASHES\s0" .PP .Vb 2 \& # one element \& $LoH[0]{lead} = "fred"; .Ve .Vb 2 \& # another element \& $LoH[1]{lead} =~ s/(\ew)/\eu$1/; .Ve .Vb 8 \& # print the whole thing with refs \& for $href ( @LoH ) { \& print "{ "; \& for $role ( keys %$href ) { \& print "$role=$href->{$role} "; \& } \& print "}\en"; \& } .Ve .Vb 8 \& # print the whole thing with indices \& for $i ( 0 .. $#LoH ) { \& print "$i is { "; \& for $role ( keys %{ $LoH[$i] } ) { \& print "$role=$LoH[$i]{$role} "; \& } \& print "}\en"; \& } .Ve .Vb 6 \& # print the whole thing one at a time \& for $i ( 0 .. $#LoH ) { \& for $role ( keys %{ $LoH[$i] } ) { \& print "elt $i $role is $LoH[$i]{$role}\en"; \& } \& } .Ve .SH "HASHES OF HASHES" .Sh "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0" .PP .Vb 16 \& %HoH = ( \& flintstones => { \& lead => "fred", \& pal => "barney", \& }, \& jetsons => { \& lead => "george", \& wife => "jane", \& "his boy" => "elroy", \& }, \& simpsons => { \& lead => "homer", \& wife => "marge", \& kid => "bart", \& }, \& ); .Ve .Sh "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0" .PP .Vb 9 \& # reading from file \& # flintstones: lead=fred pal=barney wife=wilma pet=dino \& while ( <> ) { \& next unless s/^(.*?):\es*//; \& $who = $1; \& for $field ( split ) { \& ($key, $value) = split /=/, $field; \& $HoH{$who}{$key} = $value; \& } .Ve .Vb 11 \& # reading from file; more temps \& while ( <> ) { \& next unless s/^(.*?):\es*//; \& $who = $1; \& $rec = {}; \& $HoH{$who} = $rec; \& for $field ( split ) { \& ($key, $value) = split /=/, $field; \& $rec->{$key} = $value; \& } \& } .Ve .Vb 4 \& # calling a function that returns a key,value hash \& for $group ( "simpsons", "jetsons", "flintstones" ) { \& $HoH{$group} = { get_family($group) }; \& } .Ve .Vb 5 \& # likewise, but using temps \& for $group ( "simpsons", "jetsons", "flintstones" ) { \& %members = get_family($group); \& $HoH{$group} = { %members }; \& } .Ve .Vb 5 \& # append new members to an existing family \& %new_folks = ( \& wife => "wilma", \& pet => "dino", \& ); .Ve .Vb 3 \& for $what (keys %new_folks) { \& $HoH{flintstones}{$what} = $new_folks{$what}; \& } .Ve .Sh "Access and Printing of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0" .PP .Vb 2 \& # one element \& $HoH{flintstones}{wife} = "wilma"; .Ve .Vb 2 \& # another element \& $HoH{simpsons}{lead} =~ s/(\ew)/\eu$1/; .Ve .Vb 8 \& # print the whole thing \& foreach $family ( keys %HoH ) { \& print "$family: { "; \& for $role ( keys %{ $HoH{$family} } ) { \& print "$role=$HoH{$family}{$role} "; \& } \& print "}\en"; \& } .Ve .Vb 8 \& # print the whole thing somewhat sorted \& foreach $family ( sort keys %HoH ) { \& print "$family: { "; \& for $role ( sort keys %{ $HoH{$family} } ) { \& print "$role=$HoH{$family}{$role} "; \& } \& print "}\en"; \& } .Ve .Vb 8 \& # print the whole thing sorted by number of members \& foreach $family ( sort { keys %{$HoH{$b}} <=> keys %{$HoH{$a}} } keys %HoH ) { \& print "$family: { "; \& for $role ( sort keys %{ $HoH{$family} } ) { \& print "$role=$HoH{$family}{$role} "; \& } \& print "}\en"; \& } .Ve .Vb 3 \& # establish a sort order (rank) for each role \& $i = 0; \& for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i } .Ve .Vb 9 \& # now print the whole thing sorted by number of members \& foreach $family ( sort { keys %{ $HoH{$b} } <=> keys %{ $HoH{$a} } } keys %HoH ) { \& print "$family: { "; \& # and print these according to rank order \& for $role ( sort { $rank{$a} <=> $rank{$b} } keys %{ $HoH{$family} } ) { \& print "$role=$HoH{$family}{$role} "; \& } \& print "}\en"; \& } .Ve .SH "MORE ELABORATE RECORDS" .Sh "Declaration of \s-1MORE\s0 \s-1ELABORATE\s0 \s-1RECORDS\s0" Here's a sample showing how to create and use a record whose fields are of many different sorts: .PP .Vb 8 \& $rec = { \& TEXT => $string, \& SEQUENCE => [ @old_values ], \& LOOKUP => { %some_table }, \& THATCODE => \e&some_function, \& THISCODE => sub { $_[0] ** $_[1] }, \& HANDLE => \e*STDOUT, \& }; .Ve .Vb 1 \& print $rec->{TEXT}; .Ve .Vb 2 \& print $rec->{SEQUENCE}[0]; \& $last = pop @ { $rec->{SEQUENCE} }; .Ve .Vb 2 \& print $rec->{LOOKUP}{"key"}; \& ($first_k, $first_v) = each %{ $rec->{LOOKUP} }; .Ve .Vb 2 \& $answer = $rec->{THATCODE}->($arg); \& $answer = $rec->{THISCODE}->($arg1, $arg2); .Ve .Vb 2 \& # careful of extra block braces on fh ref \& print { $rec->{HANDLE} } "a string\en"; .Ve .Vb 3 \& use FileHandle; \& $rec->{HANDLE}->autoflush(1); \& $rec->{HANDLE}->print(" a string\en"); .Ve .Sh "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1COMPLEX\s0 \s-1RECORDS\s0" .PP .Vb 10 \& %TV = ( \& flintstones => { \& series => "flintstones", \& nights => [ qw(monday thursday friday) ], \& members => [ \& { name => "fred", role => "lead", age => 36, }, \& { name => "wilma", role => "wife", age => 31, }, \& { name => "pebbles", role => "kid", age => 4, }, \& ], \& }, .Ve .Vb 9 \& jetsons => { \& series => "jetsons", \& nights => [ qw(wednesday saturday) ], \& members => [ \& { name => "george", role => "lead", age => 41, }, \& { name => "jane", role => "wife", age => 39, }, \& { name => "elroy", role => "kid", age => 9, }, \& ], \& }, .Ve .Vb 10 \& simpsons => { \& series => "simpsons", \& nights => [ qw(monday) ], \& members => [ \& { name => "homer", role => "lead", age => 34, }, \& { name => "marge", role => "wife", age => 37, }, \& { name => "bart", role => "kid", age => 11, }, \& ], \& }, \& ); .Ve .Sh "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1COMPLEX\s0 \s-1RECORDS\s0" .PP .Vb 5 \& # reading from file \& # this is most easily done by having the file itself be \& # in the raw data format as shown above. perl is happy \& # to parse complex data structures if declared as data, so \& # sometimes it's easiest to do that .Ve .Vb 4 \& # here's a piece by piece build up \& $rec = {}; \& $rec->{series} = "flintstones"; \& $rec->{nights} = [ find_days() ]; .Ve .Vb 7 \& @members = (); \& # assume this file in field=value syntax \& while (<>) { \& %fields = split /[\es=]+/; \& push @members, { %fields }; \& } \& $rec->{members} = [ @members ]; .Ve .Vb 2 \& # now remember the whole thing \& $TV{ $rec->{series} } = $rec; .Ve .Vb 19 \& ########################################################### \& # now, you might want to make interesting extra fields that \& # include pointers back into the same data structure so if \& # change one piece, it changes everywhere, like for examples \& # if you wanted a {kids} field that was an array reference \& # to a list of the kids' records without having duplicate \& # records and thus update problems. \& ########################################################### \& foreach $family (keys %TV) { \& $rec = $TV{$family}; # temp pointer \& @kids = (); \& for $person ( @{ $rec->{members} } ) { \& if ($person->{role} =~ /kid|son|daughter/) { \& push @kids, $person; \& } \& } \& # REMEMBER: $rec and $TV{$family} point to same data!! \& $rec->{kids} = [ @kids ]; \& } .Ve .Vb 3 \& # you copied the list, but the list itself contains pointers \& # to uncopied objects. this means that if you make bart get \& # older via .Ve .Vb 1 \& $TV{simpsons}{kids}[0]{age}++; .Ve .Vb 2 \& # then this would also change in \& print $TV{simpsons}{members}[2]{age}; .Ve .Vb 2 \& # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2] \& # both point to the same underlying anonymous hash table .Ve .Vb 13 \& # print the whole thing \& foreach $family ( keys %TV ) { \& print "the $family"; \& print " is on during @{ $TV{$family}{nights} }\en"; \& print "its members are:\en"; \& for $who ( @{ $TV{$family}{members} } ) { \& print " $who->{name} ($who->{role}), age $who->{age}\en"; \& } \& print "it turns out that $TV{$family}{lead} has "; \& print scalar ( @{ $TV{$family}{kids} } ), " kids named "; \& print join (", ", map { $_->{name} } @{ $TV{$family}{kids} } ); \& print "\en"; \& } .Ve .SH "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 the \fIperlmodlib\fR manpage for source code to MLDBM. .SH "SEE ALSO" \fIperlref\fR\|(1), \fIperllol\fR\|(1), \fIperldata\fR\|(1), \fIperlobj\fR\|(1) .SH "AUTHOR" Tom Christiansen <\fItchrist@perl.com\fR> .PP Last update: Wed Oct 23 04:57:50 MET DST 1996 .rn }` '' .IX Title "PERLDSC 1" .IX Name "perldsc - Perl Data Structures Cookbook" .IX Header "NAME" .IX Header "DESCRIPTION" .IX Item "\(bu arrays of arrays" .IX Item "\(bu hashes of arrays" .IX Item "\(bu arrays of hashes" .IX Item "\(bu hashes of hashes" .IX Item "\(bu more elaborate constructs" .IX Header "REFERENCES" .IX Header "COMMON MISTAKES" .IX Header "CAVEAT ON PRECEDENCE" .IX Header "WHY YOU SHOULD ALWAYS \f(CWuse strict\fR" .IX Header "DEBUGGING" .IX Header "CODE EXAMPLES" .IX Header "LISTS OF LISTS" .IX Subsection "Declaration of a \s-1LIST\s0 \s-1OF\s0 \s-1LISTS\s0" .IX Subsection "Generation of a \s-1LIST\s0 \s-1OF\s0 \s-1LISTS\s0" .IX Subsection "Access and Printing of a \s-1LIST\s0 \s-1OF\s0 \s-1LISTS\s0" .IX Header "HASHES OF LISTS" .IX Subsection "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1LISTS\s0" .IX Subsection "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1LISTS\s0" .IX Subsection "Access and Printing of a \s-1HASH\s0 \s-1OF\s0 \s-1LISTS\s0" .IX Header "LISTS OF HASHES" .IX Subsection "Declaration of a \s-1LIST\s0 \s-1OF\s0 \s-1HASHES\s0" .IX Subsection "Generation of a \s-1LIST\s0 \s-1OF\s0 \s-1HASHES\s0" .IX Subsection "Access and Printing of a \s-1LIST\s0 \s-1OF\s0 \s-1HASHES\s0" .IX Header "HASHES OF HASHES" .IX Subsection "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0" .IX Subsection "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0" .IX Subsection "Access and Printing of a \s-1HASH\s0 \s-1OF\s0 \s-1HASHES\s0" .IX Header "MORE ELABORATE RECORDS" .IX Subsection "Declaration of \s-1MORE\s0 \s-1ELABORATE\s0 \s-1RECORDS\s0" .IX Subsection "Declaration of a \s-1HASH\s0 \s-1OF\s0 \s-1COMPLEX\s0 \s-1RECORDS\s0" .IX Subsection "Generation of a \s-1HASH\s0 \s-1OF\s0 \s-1COMPLEX\s0 \s-1RECORDS\s0" .IX Header "Database Ties" .IX Header "SEE ALSO" .IX Header "AUTHOR"