Debian Codegraph @

upstream/debian-unstable/man1/perldsc.1

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\" ========================================================================
56 .\"
57 .IX Title "PERLDSC 1"
58 .TH PERLDSC 1 2025-11-16 "perl v5.40.1" "Perl Programmers Reference Guide"
59 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
60 .\" way too many mistakes in technical documents.
61 .if n .ad l
62 .nh
63 .SH NAME
64 perldsc \- Perl Data Structures Cookbook
65 .IX Xref "data structure complex data structure struct"
66 .SH DESCRIPTION
67 .IX Header "DESCRIPTION"
68 Perl lets us have complex data structures. You can write something like
69 this and all of a sudden, you'd have an array with three dimensions!
70 .PP
71 .Vb 8
72 \& for my $x (1 .. 10) {
73 \& for my $y (1 .. 10) {
74 \& for my $z (1 .. 10) {
75 \& $AoA[$x][$y][$z] =
76 \& $x ** $y + $z;
77 \& }
78 \& }
79 \& }
80 .Ve
81 .PP
82 Alas, however simple this may appear, underneath it's a much more
83 elaborate construct than meets the eye!
84 .PP
85 How do you print it out? Why can't you say just \f(CW\*(C`print @AoA\*(C'\fR? How do
86 you sort it? How can you pass it to a function or get one of these back
87 from a function? Is it an object? Can you save it to disk to read
88 back later? How do you access whole rows or columns of that matrix? Do
89 all the values have to be numeric?
90 .PP
91 As you see, it's quite easy to become confused. While some small portion
92 of the blame for this can be attributed to the reference-based
93 implementation, it's really more due to a lack of existing documentation with
94 examples designed for the beginner.
95 .PP
96 This document is meant to be a detailed but understandable treatment of the
97 many different sorts of data structures you might want to develop. It
98 should also serve as a cookbook of examples. That way, when you need to
99 create one of these complex data structures, you can just pinch, pilfer, or
100 purloin a drop-in example from here.
101 .PP
102 Let's look at each of these possible constructs in detail. There are separate
103 sections on each of the following:
104 .IP \(bu 5
105 arrays of arrays
106 .IP \(bu 5
107 hashes of arrays
108 .IP \(bu 5
109 arrays of hashes
110 .IP \(bu 5
111 hashes of hashes
112 .IP \(bu 5
113 more elaborate constructs
114 .PP
115 But for now, let's look at general issues common to all
116 these types of data structures.
117 .SH REFERENCES
118 .IX Xref "reference dereference dereferencing pointer"
119 .IX Header "REFERENCES"
120 The most important thing to understand about all data structures in
121 Perl\-\-including multidimensional arrays\-\-is that even though they might
122 appear otherwise, Perl \f(CW@ARRAY\fRs and \f(CW%HASH\fRes are all internally
123 one-dimensional. They can hold only scalar values (meaning a string,
124 number, or a reference). They cannot directly contain other arrays or
125 hashes, but instead contain \fIreferences\fR to other arrays or hashes.
126 .IX Xref "multidimensional array array, multidimensional"
127 .PP
128 You can't use a reference to an array or hash in quite the same way that you
129 would a real array or hash. For C or C++ programmers unused to
130 distinguishing between arrays and pointers to the same, this can be
131 confusing. If so, just think of it as the difference between a structure
132 and a pointer to a structure.
133 .PP
134 You can (and should) read more about references in perlref.
135 Briefly, references are rather like pointers that know what they
136 point to. (Objects are also a kind of reference, but we won't be needing
137 them right away\-\-if ever.) This means that when you have something which
138 looks to you like an access to a two-or-more-dimensional array and/or hash,
139 what's really going on is that the base type is
140 merely a one-dimensional entity that contains references to the next
141 level. It's just that you can \fIuse\fR it as though it were a
142 two-dimensional one. This is actually the way almost all C
143 multidimensional arrays work as well.
144 .PP
145 .Vb 4
146 \& $array[7][12] # array of arrays
147 \& $array[7]{string} # array of hashes
148 \& $hash{string}[7] # hash of arrays
149 \& $hash{string}{\*(Aqanother string\*(Aq} # hash of hashes
150 .Ve
151 .PP
152 Now, because the top level contains only references, if you try to print
153 out your array in with a simple \fBprint()\fR function, you'll get something
154 that doesn't look very nice, like this:
155 .PP
156 .Vb 5
157 \& my @AoA = ( [2, 3], [4, 5, 7], [0] );
158 \& print $AoA[1][2];
159 \& 7
160 \& print @AoA;
161 \& ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)
162 .Ve
163 .PP
164 That's because Perl doesn't (ever) implicitly dereference your variables.
165 If you want to get at the thing a reference is referring to, then you have
166 to do this yourself using either prefix typing indicators, like
167 \&\f(CW\*(C`${$blah}\*(C'\fR, \f(CW\*(C`@{$blah}\*(C'\fR, \f(CW\*(C`@{$blah[$i]}\*(C'\fR, or else postfix pointer arrows,
168 like \f(CW\*(C`$arr\->[3]\*(C'\fR, \f(CW\*(C`$hash\->{fred}\*(C'\fR, or even \f(CW\*(C`$obj\->method()\->[3]\*(C'\fR.
169 .SH "COMMON MISTAKES"
170 .IX Header "COMMON MISTAKES"
171 The two most common mistakes made in constructing something like
172 an array of arrays is either accidentally counting the number of
173 elements or else taking a reference to the same memory location
174 repeatedly. Here's the case where you just get the count instead
175 of a nested array:
176 .PP
177 .Vb 4
178 \& for my $i (1..10) {
179 \& my @array = somefunc($i);
180 \& $AoA[$i] = @array; # WRONG!
181 \& }
182 .Ve
183 .PP
184 That's just the simple case of assigning an array to a scalar and getting
185 its element count. If that's what you really and truly want, then you
186 might do well to consider being a tad more explicit about it, like this:
187 .PP
188 .Vb 4
189 \& for my $i (1..10) {
190 \& my @array = somefunc($i);
191 \& $counts[$i] = scalar @array;
192 \& }
193 .Ve
194 .PP
195 Here's the case of taking a reference to the same memory location
196 again and again:
197 .PP
198 .Vb 2
199 \& # Either without strict or having an outer\-scope my @array;
200 \& # declaration.
201 \&
202 \& for my $i (1..10) {
203 \& @array = somefunc($i);
204 \& $AoA[$i] = \e@array; # WRONG!
205 \& }
206 .Ve
207 .PP
208 So, what's the big problem with that? It looks right, doesn't it?
209 After all, I just told you that you need an array of references, so by
210 golly, you've made me one!
211 .PP
212 Unfortunately, while this is true, it's still broken. All the references
213 in \f(CW@AoA\fR refer to the \fIvery same place\fR, and they will therefore all hold
214 whatever was last in \f(CW@array\fR! It's similar to the problem demonstrated in
215 the following C program:
216 .PP
217 .Vb 5
218 \& #include <pwd.h>
219 \& main() {
220 \& struct passwd *getpwnam(), *rp, *dp;
221 \& rp = getpwnam("root");
222 \& dp = getpwnam("daemon");
223 \&
224 \& printf("daemon name is %s\enroot name is %s\en",
225 \& dp\->pw_name, rp\->pw_name);
226 \& }
227 .Ve
228 .PP
229 Which will print
230 .PP
231 .Vb 2
232 \& daemon name is daemon
233 \& root name is daemon
234 .Ve
235 .PP
236 The problem is that both \f(CW\*(C`rp\*(C'\fR and \f(CW\*(C`dp\*(C'\fR are pointers to the same location
237 in memory! In C, you'd have to remember to \fBmalloc()\fR yourself some new
238 memory. In Perl, you'll want to use the array constructor \f(CW\*(C`[]\*(C'\fR or the
239 hash constructor \f(CW\*(C`{}\*(C'\fR instead. Here's the right way to do the preceding
240 broken code fragments:
241 .IX Xref "[] {}"
242 .PP
243 .Vb 2
244 \& # Either without strict or having an outer\-scope my @array;
245 \& # declaration.
246 \&
247 \& for my $i (1..10) {
248 \& @array = somefunc($i);
249 \& $AoA[$i] = [ @array ];
250 \& }
251 .Ve
252 .PP
253 The square brackets make a reference to a new array with a \fIcopy\fR
254 of what's in \f(CW@array\fR at the time of the assignment. This is what
255 you want.
256 .PP
257 Note that this will produce something similar:
258 .PP
259 .Vb 6
260 \& # Either without strict or having an outer\-scope my @array;
261 \& # declaration.
262 \& for my $i (1..10) {
263 \& @array = 0 .. $i;
264 \& $AoA[$i]\->@* = @array;
265 \& }
266 .Ve
267 .PP
268 Is it the same? Well, maybe so\-\-and maybe not. The subtle difference
269 is that when you assign something in square brackets, you know for sure
270 it's always a brand new reference with a new \fIcopy\fR of the data.
271 Something else could be going on in this new case with the
272 \&\f(CW\*(C`$AoA[$i]\->@*\*(C'\fR dereference on the left-hand-side of the assignment.
273 It all depends on whether \f(CW$AoA[$i]\fR had been undefined to start with,
274 or whether it already contained a reference. If you had already
275 populated \f(CW@AoA\fR with references, as in
276 .PP
277 .Vb 1
278 \& $AoA[3] = \e@another_array;
279 .Ve
280 .PP
281 Then the assignment with the indirection on the left-hand-side would
282 use the existing reference that was already there:
283 .PP
284 .Vb 1
285 \& $AoA[3]\->@* = @array;
286 .Ve
287 .PP
288 Of course, this \fIwould\fR have the "interesting" effect of clobbering
289 \&\f(CW@another_array\fR. (Have you ever noticed how when a programmer says
290 something is "interesting", that rather than meaning "intriguing",
291 they're disturbingly more apt to mean that it's "annoying",
292 "difficult", or both? :\-)
293 .PP
294 So just remember always to use the array or hash constructors with \f(CW\*(C`[]\*(C'\fR
295 or \f(CW\*(C`{}\*(C'\fR, and you'll be fine, although it's not always optimally
296 efficient.
297 .PP
298 Surprisingly, the following dangerous-looking construct will
299 actually work out fine:
300 .PP
301 .Vb 4
302 \& for my $i (1..10) {
303 \& my @array = somefunc($i);
304 \& $AoA[$i] = \e@array;
305 \& }
306 .Ve
307 .PP
308 That's because \fBmy()\fR is more of a run-time statement than it is a
309 compile-time declaration \fIper se\fR. This means that the \fBmy()\fR variable is
310 remade afresh each time through the loop. So even though it \fIlooks\fR as
311 though you stored the same variable reference each time, you actually did
312 not! This is a subtle distinction that can produce more efficient code at
313 the risk of misleading all but the most experienced of programmers. So I
314 usually advise against teaching it to beginners. In fact, except for
315 passing arguments to functions, I seldom like to see the gimme-a-reference
316 operator (backslash) used much at all in code. Instead, I advise
317 beginners that they (and most of the rest of us) should try to use the
318 much more easily understood constructors \f(CW\*(C`[]\*(C'\fR and \f(CW\*(C`{}\*(C'\fR instead of
319 relying upon lexical (or dynamic) scoping and hidden reference-counting to
320 do the right thing behind the scenes.
321 .PP
322 Note also that there exists another way to write a dereference! These
323 two lines are equivalent:
324 .PP
325 .Vb 2
326 \& $AoA[$i]\->@* = @array;
327 \& @{ $AoA[$i] } = @array;
328 .Ve
329 .PP
330 The first form, called \fIpostfix dereference\fR is generally easier to
331 read, because the expression can be read from left to right, and there
332 are no enclosing braces to balance. On the other hand, it is also
333 newer. It was added to the language in 2014, so you will often
334 encounter the other form, \fIcircumfix dereference\fR, in older code.
335 .PP
336 In summary:
337 .PP
338 .Vb 4
339 \& $AoA[$i] = [ @array ]; # usually best
340 \& $AoA[$i] = \e@array; # perilous; just how my() was that array?
341 \& $AoA[$i]\->@* = @array; # way too tricky for most programmers
342 \& @{ $AoA[$i] } = @array; # just as tricky, and also harder to read
343 .Ve
344 .SH "CAVEAT ON PRECEDENCE"
345 .IX Xref "dereference, precedence dereferencing, precedence"
346 .IX Header "CAVEAT ON PRECEDENCE"
347 Speaking of things like \f(CW\*(C`@{$AoA[$i]}\*(C'\fR, the following are actually the
348 same thing:
349 .IX Xref "->"
350 .PP
351 .Vb 2
352 \& $aref\->[2][2] # clear
353 \& $$aref[2][2] # confusing
354 .Ve
355 .PP
356 That's because Perl's precedence rules on its five prefix dereferencers
357 (which look like someone swearing: \f(CW\*(C`$ @ * % &\*(C'\fR) make them bind more
358 tightly than the postfix subscripting brackets or braces! This will no
359 doubt come as a great shock to the C or C++ programmer, who is quite
360 accustomed to using \f(CW*a[i]\fR to mean what's pointed to by the \fIi'th\fR
361 element of \f(CW\*(C`a\*(C'\fR. That is, they first take the subscript, and only then
362 dereference the thing at that subscript. That's fine in C, but this isn't C.
363 .PP
364 The seemingly equivalent construct in Perl, \f(CW$$aref[$i]\fR first does
365 the deref of \f(CW$aref\fR, making it take \f(CW$aref\fR as a reference to an
366 array, and then dereference that, and finally tell you the \fIi'th\fR value
367 of the array pointed to by \f(CW$AoA\fR. If you wanted the C notion, you could
368 write \f(CW\*(C`$AoA[$i]\->$*\*(C'\fR to explicitly dereference the \fIi'th\fR item,
369 reading left to right.
370 .ie n .SH "WHY YOU SHOULD ALWAYS ""use VERSION"""
371 .el .SH "WHY YOU SHOULD ALWAYS \f(CWuse VERSION\fP"
372 .IX Header "WHY YOU SHOULD ALWAYS use VERSION"
373 If this is starting to sound scarier than it's worth, relax. Perl has
374 some features to help you avoid its most common pitfalls. One way to avoid
375 getting confused is to start every program with:
376 .PP
377 .Vb 1
378 \& use strict;
379 .Ve
380 .PP
381 This way, you'll be forced to declare all your variables with \fBmy()\fR and
382 also disallow accidental "symbolic dereferencing". Therefore if you'd done
383 this:
384 .PP
385 .Vb 5
386 \& my $aref = [
387 \& [ "fred", "barney", "pebbles", "bambam", "dino", ],
388 \& [ "homer", "bart", "marge", "maggie", ],
389 \& [ "george", "jane", "elroy", "judy", ],
390 \& ];
391 \&
392 \& print $aref[2][2];
393 .Ve
394 .PP
395 The compiler would immediately flag that as an error \fIat compile time\fR,
396 because you were accidentally accessing \f(CW@aref\fR, an undeclared
397 variable, and it would thereby remind you to write instead:
398 .PP
399 .Vb 1
400 \& print $aref\->[2][2]
401 .Ve
402 .PP
403 Since Perl version 5.12, a \f(CW\*(C`use VERSION\*(C'\fR declaration will also enable the
404 \&\f(CW\*(C`strict\*(C'\fR pragma. In addition, it will also enable a feature bundle,
405 giving more useful features. Since version 5.36 it will also enable the
406 \&\f(CW\*(C`warnings\*(C'\fR pragma. Often the best way to activate all these things at
407 once is to start a file with:
408 .PP
409 .Vb 1
410 \& use v5.36;
411 .Ve
412 .PP
413 In this way, every file will start with \f(CW\*(C`strict\*(C'\fR, \f(CW\*(C`warnings\*(C'\fR, and many
414 useful named features all switched on, as well as several older features
415 being switched off (such as \f(CW\*(C`indirect\*(C'\fR).
416 For more information, see "use VERSION" in perlfunc.
417 .SH DEBUGGING
418 .IX Xref "data structure, debugging complex data structure, debugging AoA, debugging HoA, debugging AoH, debugging HoH, debugging array of arrays, debugging hash of arrays, debugging array of hashes, debugging hash of hashes, debugging"
419 .IX Header "DEBUGGING"
420 You can use the debugger's \f(CW\*(C`x\*(C'\fR command to dump out complex data structures.
421 For example, given the assignment to \f(CW$AoA\fR above, here's the debugger output:
422 .PP
423 .Vb 10
424 \& DB<1> x $AoA
425 \& $AoA = ARRAY(0x13b5a0)
426 \& 0 ARRAY(0x1f0a24)
427 \& 0 \*(Aqfred\*(Aq
428 \& 1 \*(Aqbarney\*(Aq
429 \& 2 \*(Aqpebbles\*(Aq
430 \& 3 \*(Aqbambam\*(Aq
431 \& 4 \*(Aqdino\*(Aq
432 \& 1 ARRAY(0x13b558)
433 \& 0 \*(Aqhomer\*(Aq
434 \& 1 \*(Aqbart\*(Aq
435 \& 2 \*(Aqmarge\*(Aq
436 \& 3 \*(Aqmaggie\*(Aq
437 \& 2 ARRAY(0x13b540)
438 \& 0 \*(Aqgeorge\*(Aq
439 \& 1 \*(Aqjane\*(Aq
440 \& 2 \*(Aqelroy\*(Aq
441 \& 3 \*(Aqjudy\*(Aq
442 .Ve
443 .SH "CODE EXAMPLES"
444 .IX Header "CODE EXAMPLES"
445 Presented with little comment here are short code examples illustrating
446 access of various types of data structures.
447 .SH "ARRAYS OF ARRAYS"
448 .IX Xref "array of arrays AoA"
449 .IX Header "ARRAYS OF ARRAYS"
450 .SS "Declaration of an ARRAY OF ARRAYS"
451 .IX Subsection "Declaration of an ARRAY OF ARRAYS"
452 .Vb 5
453 \& my @AoA = (
454 \& [ "fred", "barney" ],
455 \& [ "george", "jane", "elroy" ],
456 \& [ "homer", "marge", "bart" ],
457 \& );
458 .Ve
459 .SS "Generation of an ARRAY OF ARRAYS"
460 .IX Subsection "Generation of an ARRAY OF ARRAYS"
461 .Vb 4
462 \& # reading from file
463 \& while ( <> ) {
464 \& push @AoA, [ split ];
465 \& }
466 \&
467 \& # calling a function
468 \& for my $i ( 1 .. 10 ) {
469 \& $AoA[$i] = [ somefunc($i) ];
470 \& }
471 \&
472 \& # using temp vars
473 \& for my $i ( 1 .. 10 ) {
474 \& my @tmp = somefunc($i);
475 \& $AoA[$i] = [ @tmp ];
476 \& }
477 \&
478 \& # add to an existing row
479 \& push $AoA[0]\->@*, "wilma", "betty";
480 .Ve
481 .SS "Access and Printing of an ARRAY OF ARRAYS"
482 .IX Subsection "Access and Printing of an ARRAY OF ARRAYS"
483 .Vb 2
484 \& # one element
485 \& $AoA[0][0] = "Fred";
486 \&
487 \& # another element
488 \& $AoA[1][1] =~ s/(\ew)/\eu$1/;
489 \&
490 \& # print the whole thing with refs
491 \& for my $aref ( @AoA ) {
492 \& print "\et [ @$aref ],\en";
493 \& }
494 \&
495 \& # print the whole thing with indices
496 \& for my $i ( 0 .. $#AoA ) {
497 \& print "\et [ $AoA[$i]\->@* ],\en";
498 \& }
499 \&
500 \& # print the whole thing one at a time
501 \& for my $i ( 0 .. $#AoA ) {
502 \& for my $j ( 0 .. $AoA[$i]\->$#* ) {
503 \& print "elem at ($i, $j) is $AoA[$i][$j]\en";
504 \& }
505 \& }
506 .Ve
507 .SH "HASHES OF ARRAYS"
508 .IX Xref "hash of arrays HoA"
509 .IX Header "HASHES OF ARRAYS"
510 .SS "Declaration of a HASH OF ARRAYS"
511 .IX Subsection "Declaration of a HASH OF ARRAYS"
512 .Vb 5
513 \& my %HoA = (
514 \& flintstones => [ "fred", "barney" ],
515 \& jetsons => [ "george", "jane", "elroy" ],
516 \& simpsons => [ "homer", "marge", "bart" ],
517 \& );
518 .Ve
519 .SS "Generation of a HASH OF ARRAYS"
520 .IX Subsection "Generation of a HASH OF ARRAYS"
521 .Vb 6
522 \& # reading from file
523 \& # flintstones: fred barney wilma dino
524 \& while ( <> ) {
525 \& next unless s/^(.*?):\es*//;
526 \& $HoA{$1} = [ split ];
527 \& }
528 \&
529 \& # reading from file; more temps
530 \& # flintstones: fred barney wilma dino
531 \& while ( my $line = <> ) {
532 \& my ($who, $rest) = split /:\es*/, $line, 2;
533 \& my @fields = split \*(Aq \*(Aq, $rest;
534 \& $HoA{$who} = [ @fields ];
535 \& }
536 \&
537 \& # calling a function that returns a list
538 \& for my $group ( "simpsons", "jetsons", "flintstones" ) {
539 \& $HoA{$group} = [ get_family($group) ];
540 \& }
541 \&
542 \& # likewise, but using temps
543 \& for my $group ( "simpsons", "jetsons", "flintstones" ) {
544 \& my @members = get_family($group);
545 \& $HoA{$group} = [ @members ];
546 \& }
547 \&
548 \& # append new members to an existing family
549 \& push $HoA{flintstones}\->@*, "wilma", "betty";
550 .Ve
551 .SS "Access and Printing of a HASH OF ARRAYS"
552 .IX Subsection "Access and Printing of a HASH OF ARRAYS"
553 .Vb 2
554 \& # one element
555 \& $HoA{flintstones}[0] = "Fred";
556 \&
557 \& # another element
558 \& $HoA{simpsons}[1] =~ s/(\ew)/\eu$1/;
559 \&
560 \& # print the whole thing
561 \& foreach my $family ( keys %HoA ) {
562 \& print "$family: $HoA{$family}\->@* \en"
563 \& }
564 \&
565 \& # print the whole thing with indices
566 \& foreach my $family ( keys %HoA ) {
567 \& print "family: ";
568 \& foreach my $i ( 0 .. $HoA{$family}\->$#* ) {
569 \& print " $i = $HoA{$family}[$i]";
570 \& }
571 \& print "\en";
572 \& }
573 \&
574 \& # print the whole thing sorted by number of members
575 \& foreach my $family ( sort { $HoA{$b}\->@* <=> $HoA{$a}\->@* } keys %HoA ) {
576 \& print "$family: $HoA{$family}\->@* \en"
577 \& }
578 \&
579 \& # print the whole thing sorted by number of members and name
580 \& foreach my $family ( sort {
581 \& $HoA{$b}\->@* <=> $HoA{$a}\->@*
582 \& ||
583 \& $a cmp $b
584 \& } keys %HoA )
585 \& {
586 \& print "$family: ", join(", ", sort $HoA{$family}\->@* ), "\en";
587 \& }
588 .Ve
589 .SH "ARRAYS OF HASHES"
590 .IX Xref "array of hashes AoH"
591 .IX Header "ARRAYS OF HASHES"
592 .SS "Declaration of an ARRAY OF HASHES"
593 .IX Subsection "Declaration of an ARRAY OF HASHES"
594 .Vb 10
595 \& my @AoH = (
596 \& {
597 \& Lead => "fred",
598 \& Friend => "barney",
599 \& },
600 \& {
601 \& Lead => "george",
602 \& Wife => "jane",
603 \& Son => "elroy",
604 \& },
605 \& {
606 \& Lead => "homer",
607 \& Wife => "marge",
608 \& Son => "bart",
609 \& }
610 \& );
611 .Ve
612 .SS "Generation of an ARRAY OF HASHES"
613 .IX Subsection "Generation of an ARRAY OF HASHES"
614 .Vb 10
615 \& # reading from file
616 \& # format: LEAD=fred FRIEND=barney
617 \& while ( <> ) {
618 \& my $rec = {};
619 \& for my $field ( split ) {
620 \& my ($key, $value) = split /=/, $field;
621 \& $rec\->{$key} = $value;
622 \& }
623 \& push @AoH, $rec;
624 \& }
625 \&
626 \&
627 \& # reading from file
628 \& # format: LEAD=fred FRIEND=barney
629 \& # no temp
630 \& while ( <> ) {
631 \& push @AoH, { split /[\es+=]/ };
632 \& }
633 \&
634 \& # calling a function that returns a key/value pair list, like
635 \& # "lead","fred","daughter","pebbles"
636 \& while ( my %fields = getnextpairset() ) {
637 \& push @AoH, { %fields };
638 \& }
639 \&
640 \& # likewise, but using no temp vars
641 \& while (<>) {
642 \& push @AoH, { parsepairs($_) };
643 \& }
644 \&
645 \& # add key/value to an element
646 \& $AoH[0]{pet} = "dino";
647 \& $AoH[2]{pet} = "santa\*(Aqs little helper";
648 .Ve
649 .SS "Access and Printing of an ARRAY OF HASHES"
650 .IX Subsection "Access and Printing of an ARRAY OF HASHES"
651 .Vb 2
652 \& # one element
653 \& $AoH[0]{lead} = "fred";
654 \&
655 \& # another element
656 \& $AoH[1]{lead} =~ s/(\ew)/\eu$1/;
657 \&
658 \& # print the whole thing with refs
659 \& for my $href ( @AoH ) {
660 \& print "{ ";
661 \& for my $role ( keys %$href ) {
662 \& print "$role=$href\->{$role} ";
663 \& }
664 \& print "}\en";
665 \& }
666 \&
667 \& # print the whole thing with indices
668 \& for my $i ( 0 .. $#AoH ) {
669 \& print "$i is { ";
670 \& for my $role ( keys $AoH[$i]\->%* ) {
671 \& print "$role=$AoH[$i]{$role} ";
672 \& }
673 \& print "}\en";
674 \& }
675 \&
676 \& # print the whole thing one at a time
677 \& for my $i ( 0 .. $#AoH ) {
678 \& for my $role ( keys $AoH[$i]\->%* ) {
679 \& print "elem at ($i, $role) is $AoH[$i]{$role}\en";
680 \& }
681 \& }
682 .Ve
683 .SH "HASHES OF HASHES"
684 .IX Xref "hash of hashes HoH"
685 .IX Header "HASHES OF HASHES"
686 .SS "Declaration of a HASH OF HASHES"
687 .IX Subsection "Declaration of a HASH OF HASHES"
688 .Vb 10
689 \& my %HoH = (
690 \& flintstones => {
691 \& lead => "fred",
692 \& pal => "barney",
693 \& },
694 \& jetsons => {
695 \& lead => "george",
696 \& wife => "jane",
697 \& "his boy" => "elroy",
698 \& },
699 \& simpsons => {
700 \& lead => "homer",
701 \& wife => "marge",
702 \& kid => "bart",
703 \& },
704 \& );
705 .Ve
706 .SS "Generation of a HASH OF HASHES"
707 .IX Subsection "Generation of a HASH OF HASHES"
708 .Vb 10
709 \& # reading from file
710 \& # flintstones: lead=fred pal=barney wife=wilma pet=dino
711 \& while ( <> ) {
712 \& next unless s/^(.*?):\es*//;
713 \& my $who = $1;
714 \& for my $field ( split ) {
715 \& my ($key, $value) = split /=/, $field;
716 \& $HoH{$who}{$key} = $value;
717 \& }
718 \& }
719 \&
720 \&
721 \& # reading from file; more temps
722 \& while ( <> ) {
723 \& next unless s/^(.*?):\es*//;
724 \& my $who = $1;
725 \& my $rec = {};
726 \& $HoH{$who} = $rec;
727 \& for my $field ( split ) {
728 \& my ($key, $value) = split /=/, $field;
729 \& $rec\->{$key} = $value;
730 \& }
731 \& }
732 \&
733 \& # calling a function that returns a key,value hash
734 \& for my $group ( "simpsons", "jetsons", "flintstones" ) {
735 \& $HoH{$group} = { get_family($group) };
736 \& }
737 \&
738 \& # likewise, but using temps
739 \& for my $group ( "simpsons", "jetsons", "flintstones" ) {
740 \& my %members = get_family($group);
741 \& $HoH{$group} = { %members };
742 \& }
743 \&
744 \& # append new members to an existing family
745 \& my %new_folks = (
746 \& wife => "wilma",
747 \& pet => "dino",
748 \& );
749 \&
750 \& for my $what (keys %new_folks) {
751 \& $HoH{flintstones}{$what} = $new_folks{$what};
752 \& }
753 \&
754 \& # same, but using a hash slice
755 \& @{ $HoH{flintstones} }{ keys %new_folks } = values %new_folks;
756 \&
757 \& # same, but without a %new_folks variable
758 \& @{ $HoH{flintstones} }{ "wife", "pet" } = ( "wilma", "dino" );
759 .Ve
760 .SS "Access and Printing of a HASH OF HASHES"
761 .IX Subsection "Access and Printing of a HASH OF HASHES"
762 .Vb 2
763 \& # one element
764 \& $HoH{flintstones}{wife} = "wilma";
765 \&
766 \& # another element
767 \& $HoH{simpsons}{lead} =~ s/(\ew)/\eu$1/;
768 \&
769 \& # print the whole thing
770 \& foreach my $family ( keys %HoH ) {
771 \& print "$family: { ";
772 \& for my $role ( keys $HoH{$family}\->%* ) {
773 \& print "$role=$HoH{$family}{$role} ";
774 \& }
775 \& print "}\en";
776 \& }
777 \&
778 \& # print the whole thing somewhat sorted
779 \& foreach my $family ( sort keys %HoH ) {
780 \& print "$family: { ";
781 \& for my $role ( sort keys $HoH{$family}\->%* ) {
782 \& print "$role=$HoH{$family}{$role} ";
783 \& }
784 \& print "}\en";
785 \& }
786 \&
787 \&
788 \& # print the whole thing sorted by number of members
789 \& foreach my $family ( sort { $HoH{$b}\->%* <=> $HoH{$a}\->%* } keys %HoH ) {
790 \& print "$family: { ";
791 \& for my $role ( sort keys $HoH{$family}\->%* ) {
792 \& print "$role=$HoH{$family}{$role} ";
793 \& }
794 \& print "}\en";
795 \& }
796 \&
797 \& # establish a sort order (rank) for each role
798 \& my $i = 0;
799 \& my %rank;
800 \& for ( qw(lead wife son daughter pal pet) ) { $rank{$_} = ++$i }
801 \&
802 \& # now print the whole thing sorted by number of members
803 \& foreach my $family ( sort { $HoH{$b}\->%* <=> $HoH{$a}\->%* } keys %HoH ) {
804 \& print "$family: { ";
805 \& # and print these according to rank order
806 \& for my $role ( sort { $rank{$a} <=> $rank{$b} }
807 \& keys $HoH{$family}\->%* )
808 \& {
809 \& print "$role=$HoH{$family}{$role} ";
810 \& }
811 \& print "}\en";
812 \& }
813 .Ve
814 .SH "MORE ELABORATE RECORDS"
815 .IX Xref "record structure struct"
816 .IX Header "MORE ELABORATE RECORDS"
817 .SS "Declaration of MORE ELABORATE RECORDS"
818 .IX Subsection "Declaration of MORE ELABORATE RECORDS"
819 Here's a sample showing how to create and use a record whose fields are of
820 many different sorts:
821 .PP
822 .Vb 8
823 \& my $rec = {
824 \& TEXT => $string,
825 \& SEQUENCE => [ @old_values ],
826 \& LOOKUP => { %some_table },
827 \& THATCODE => \e&some_function,
828 \& THISCODE => sub { $_[0] ** $_[1] },
829 \& HANDLE => \e*STDOUT,
830 \& };
831 \&
832 \& print $rec\->{TEXT};
833 \&
834 \& print $rec\->{SEQUENCE}[0];
835 \& my $last = pop $rec\->{SEQUENCE}\->@*;
836 \&
837 \& print $rec\->{LOOKUP}{"key"};
838 \& my ($first_k, $first_v) = each $rec\->{LOOKUP}\->%*;
839 \&
840 \& my $answer = $rec\->{THATCODE}\->($arg);
841 \& $answer = $rec\->{THISCODE}\->($arg1, $arg2);
842 \&
843 \& # careful of extra block braces on fh ref
844 \& print { $rec\->{HANDLE} } "a string\en";
845 \&
846 \& use FileHandle;
847 \& $rec\->{HANDLE}\->autoflush(1);
848 \& $rec\->{HANDLE}\->print(" a string\en");
849 .Ve
850 .SS "Declaration of a HASH OF COMPLEX RECORDS"
851 .IX Subsection "Declaration of a HASH OF COMPLEX RECORDS"
852 .Vb 10
853 \& my %TV = (
854 \& flintstones => {
855 \& series => "flintstones",
856 \& nights => [ qw(monday thursday friday) ],
857 \& members => [
858 \& { name => "fred", role => "lead", age => 36, },
859 \& { name => "wilma", role => "wife", age => 31, },
860 \& { name => "pebbles", role => "kid", age => 4, },
861 \& ],
862 \& },
863 \&
864 \& jetsons => {
865 \& series => "jetsons",
866 \& nights => [ qw(wednesday saturday) ],
867 \& members => [
868 \& { name => "george", role => "lead", age => 41, },
869 \& { name => "jane", role => "wife", age => 39, },
870 \& { name => "elroy", role => "kid", age => 9, },
871 \& ],
872 \& },
873 \&
874 \& simpsons => {
875 \& series => "simpsons",
876 \& nights => [ qw(monday) ],
877 \& members => [
878 \& { name => "homer", role => "lead", age => 34, },
879 \& { name => "marge", role => "wife", age => 37, },
880 \& { name => "bart", role => "kid", age => 11, },
881 \& ],
882 \& },
883 \& );
884 .Ve
885 .SS "Generation of a HASH OF COMPLEX RECORDS"
886 .IX Subsection "Generation of a HASH OF COMPLEX RECORDS"
887 .Vb 5
888 \& # reading from file
889 \& # this is most easily done by having the file itself be
890 \& # in the raw data format as shown above. perl is happy
891 \& # to parse complex data structures if declared as data, so
892 \& # sometimes it\*(Aqs easiest to do that
893 \&
894 \& # here\*(Aqs a piece by piece build up
895 \& my $rec = {};
896 \& $rec\->{series} = "flintstones";
897 \& $rec\->{nights} = [ find_days() ];
898 \&
899 \& my @members = ();
900 \& # assume this file in field=value syntax
901 \& while (<>) {
902 \& my %fields = split /[\es=]+/;
903 \& push @members, { %fields };
904 \& }
905 \& $rec\->{members} = [ @members ];
906 \&
907 \& # now remember the whole thing
908 \& $TV{ $rec\->{series} } = $rec;
909 \&
910 \& ###########################################################
911 \& # now, you might want to make interesting extra fields that
912 \& # include pointers back into the same data structure so if
913 \& # change one piece, it changes everywhere, like for example
914 \& # if you wanted a {kids} field that was a reference
915 \& # to an array of the kids\*(Aq records without having duplicate
916 \& # records and thus update problems.
917 \& ###########################################################
918 \& foreach my $family (keys %TV) {
919 \& my $rec = $TV{$family}; # temp pointer
920 \& my @kids = ();
921 \& for my $person ( $rec\->{members}\->@* ) {
922 \& if ($person\->{role} =~ /kid|son|daughter/) {
923 \& push @kids, $person;
924 \& }
925 \& }
926 \& # REMEMBER: $rec and $TV{$family} point to same data!!
927 \& $rec\->{kids} = [ @kids ];
928 \& }
929 \&
930 \& # you copied the array, but the array itself contains pointers
931 \& # to uncopied objects. this means that if you make bart get
932 \& # older via
933 \&
934 \& $TV{simpsons}{kids}[0]{age}++;
935 \&
936 \& # then this would also change in
937 \& print $TV{simpsons}{members}[2]{age};
938 \&
939 \& # because $TV{simpsons}{kids}[0] and $TV{simpsons}{members}[2]
940 \& # both point to the same underlying anonymous hash table
941 \&
942 \& # print the whole thing
943 \& foreach my $family ( keys %TV ) {
944 \& print "the $family";
945 \& print " is on during $TV{$family}{nights}\->@*\en";
946 \& print "its members are:\en";
947 \& for my $who ( $TV{$family}{members}\->@* ) {
948 \& print " $who\->{name} ($who\->{role}), age $who\->{age}\en";
949 \& }
950 \& print "it turns out that $TV{$family}{lead} has ";
951 \& print scalar ( $TV{$family}{kids}\->@* ), " kids named ";
952 \& print join (", ", map { $_\->{name} } $TV{$family}{kids}\->@* );
953 \& print "\en";
954 \& }
955 .Ve
956 .SH "Database Ties"
957 .IX Header "Database Ties"
958 You cannot easily tie a multilevel data structure (such as a hash of
959 hashes) to a dbm file. The first problem is that all but GDBM and
960 Berkeley DB have size limitations, but beyond that, you also have problems
961 with how references are to be represented on disk. One experimental
962 module that does partially attempt to address this need is the MLDBM
963 module. Check your nearest CPAN site as described in perlmodlib for
964 source code to MLDBM.
965 .SH "SEE ALSO"
966 .IX Header "SEE ALSO"
967 perlref, perllol, perldata, perlobj
968 .SH AUTHOR
969 .IX Header "AUTHOR"
970 Tom Christiansen <\[email protected]\fR>