Debian Codegraph @

upstream/fedora-44/man1/perldsc.1

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