📄 perldsc.pod
字号:
=head1 NAMEX<data structure> X<complex data structure> X<struct>perldsc - Perl Data Structures Cookbook=head1 DESCRIPTIONThe single feature most sorely lacking in the Perl programming languageprior to its 5.0 release was complex data structures. Even without directlanguage support, some valiant programmers did manage to emulate them, butit was hard work and not for the faint of heart. You could occasionallyget away with the C<$m{$AoA,$b}> notation borrowed from B<awk> in which thekeys are actually more like a single concatenated string C<"$AoA$b">, buttraversal and sorting were difficult. More desperate programmers evenhacked Perl's internal symbol table directly, a strategy that proved hardto develop and maintain--to put it mildly.The 5.0 release of Perl let us have complex data structures. Youmay now write something like this and all of a sudden, you'd have an arraywith three dimensions! for $x (1 .. 10) { for $y (1 .. 10) { for $z (1 .. 10) { $AoA[$x][$y][$z] = $x ** $y + $z; } } }Alas, however simple this may appear, underneath it's a much moreelaborate construct than meets the eye!How do you print it out? Why can't you say just C<print @AoA>? How doyou sort it? How can you pass it to a function or get one of these backfrom a function? Is it an object? Can you save it to disk to readback later? How do you access whole rows or columns of that matrix? Doall the values have to be numeric?As you see, it's quite easy to become confused. While some small portionof the blame for this can be attributed to the reference-basedimplementation, it's really more due to a lack of existing documentation withexamples designed for the beginner.This document is meant to be a detailed but understandable treatment of themany different sorts of data structures you might want to develop. Itshould also serve as a cookbook of examples. That way, when you need tocreate one of these complex data structures, you can just pinch, pilfer, orpurloin a drop-in example from here.Let's look at each of these possible constructs in detail. There are separatesections on each of the following:=over 5=item * arrays of arrays=item * hashes of arrays=item * arrays of hashes=item * hashes of hashes=item * more elaborate constructs=backBut for now, let's look at general issues common to allthese types of data structures.=head1 REFERENCESX<reference> X<dereference> X<dereferencing> X<pointer>The most important thing to understand about all data structures in Perl-- including multidimensional arrays--is that even though they mightappear otherwise, Perl C<@ARRAY>s and C<%HASH>es are all internallyone-dimensional. They can hold only scalar values (meaning a string,number, or a reference). They cannot directly contain other arrays orhashes, but instead contain I<references> to other arrays or hashes.X<multidimensional array> X<array, multidimensional>You can't use a reference to an array or hash in quite the same way that youwould a real array or hash. For C or C++ programmers unused todistinguishing between arrays and pointers to the same, this can beconfusing. If so, just think of it as the difference between a structureand a pointer to a structure.You can (and should) read more about references in the perlref(1) manpage. Briefly, references are rather like pointers that know what theypoint to. (Objects are also a kind of reference, but we won't be needingthem right away--if ever.) This means that when you have something whichlooks 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 ismerely a one-dimensional entity that contains references to the nextlevel. It's just that you can I<use> it as though it were atwo-dimensional one. This is actually the way almost all Cmultidimensional arrays work as well. $array[7][12] # array of arrays $array[7]{string} # array of hashes $hash{string}[7] # hash of arrays $hash{string}{'another string'} # hash of hashesNow, because the top level contains only references, if you try to printout your array in with a simple print() function, you'll get somethingthat doesn't look very nice, like this: @AoA = ( [2, 3], [4, 5, 7], [0] ); print $AoA[1][2]; 7 print @AoA; ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0)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 haveto do this yourself using either prefix typing indicators, likeC<${$blah}>, C<@{$blah}>, C<@{$blah[$i]}>, or else postfix pointer arrows,like C<$a-E<gt>[3]>, C<$h-E<gt>{fred}>, or even C<$ob-E<gt>method()-E<gt>[3]>.=head1 COMMON MISTAKESThe two most common mistakes made in constructing something likean array of arrays is either accidentally counting the number ofelements or else taking a reference to the same memory locationrepeatedly. Here's the case where you just get the count insteadof a nested array: for $i (1..10) { @array = somefunc($i); $AoA[$i] = @array; # WRONG! }That's just the simple case of assigning an array to a scalar and gettingits element count. If that's what you really and truly want, then youmight do well to consider being a tad more explicit about it, like this: for $i (1..10) { @array = somefunc($i); $counts[$i] = scalar @array; }Here's the case of taking a reference to the same memory locationagain and again: for $i (1..10) { @array = somefunc($i); $AoA[$i] = \@array; # WRONG! }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 bygolly, you've made me one!Unfortunately, while this is true, it's still broken. All the referencesin @AoA refer to the I<very same place>, and they will therefore all holdwhatever was last in @array! It's similar to the problem demonstrated inthe following C program: #include <pwd.h> main() { struct passwd *getpwnam(), *rp, *dp; rp = getpwnam("root"); dp = getpwnam("daemon"); printf("daemon name is %s\nroot name is %s\n", dp->pw_name, rp->pw_name); }Which will print daemon name is daemon root name is daemonThe problem is that both C<rp> and C<dp> are pointers to the same locationin memory! In C, you'd have to remember to malloc() yourself some newmemory. In Perl, you'll want to use the array constructor C<[]> or thehash constructor C<{}> instead. Here's the right way to do the precedingbroken code fragments:X<[]> X<{}> for $i (1..10) { @array = somefunc($i); $AoA[$i] = [ @array ]; }The square brackets make a reference to a new array with a I<copy>of what's in @array at the time of the assignment. This is whatyou want.Note that this will produce something similar, but it'smuch harder to read: for $i (1..10) { @array = 0 .. $i; @{$AoA[$i]} = @array; }Is it the same? Well, maybe so--and maybe not. The subtle differenceis that when you assign something in square brackets, you know for sureit's always a brand new reference with a new I<copy> of the data.Something else could be going on in this new case with the C<@{$AoA[$i]}>dereference on the left-hand-side of the assignment. It all depends onwhether C<$AoA[$i]> had been undefined to start with, or whether italready contained a reference. If you had already populated @AoA withreferences, as in $AoA[3] = \@another_array;Then the assignment with the indirection on the left-hand-side woulduse the existing reference that was already there: @{$AoA[3]} = @array;Of course, this I<would> have the "interesting" effect of clobbering@another_array. (Have you ever noticed how when a programmer sayssomething is "interesting", that rather than meaning "intriguing",they're disturbingly more apt to mean that it's "annoying","difficult", or both? :-)So just remember always to use the array or hash constructors with C<[]>or C<{}>, and you'll be fine, although it's not always optimallyefficient.Surprisingly, the following dangerous-looking construct willactually work out fine: for $i (1..10) { my @array = somefunc($i); $AoA[$i] = \@array; }That's because my() is more of a run-time statement than it is acompile-time declaration I<per se>. This means that the my() variable isremade afresh each time through the loop. So even though it I<looks> asthough you stored the same variable reference each time, you actually didnot! This is a subtle distinction that can produce more efficient code atthe risk of misleading all but the most experienced of programmers. So Iusually advise against teaching it to beginners. In fact, except forpassing arguments to functions, I seldom like to see the gimme-a-referenceoperator (backslash) used much at all in code. Instead, I advisebeginners that they (and most of the rest of us) should try to use themuch more easily understood constructors C<[]> and C<{}> instead ofrelying upon lexical (or dynamic) scoping and hidden reference-counting todo the right thing behind the scenes.In summary: $AoA[$i] = [ @array ]; # usually best $AoA[$i] = \@array; # perilous; just how my() was that array? @{ $AoA[$i] } = @array; # way too tricky for most programmers=head1 CAVEAT ON PRECEDENCEX<dereference, precedence> X<dereferencing, precedence>Speaking of things like C<@{$AoA[$i]}>, the following are actually thesame thing:X<< -> >> $aref->[2][2] # clear $$aref[2][2] # confusingThat's because Perl's precedence rules on its five prefix dereferencers(which look like someone swearing: C<$ @ * % &>) make them bind moretightly than the postfix subscripting brackets or braces! This will nodoubt come as a great shock to the C or C++ programmer, who is quiteaccustomed to using C<*a[i]> to mean what's pointed to by the I<i'th>element of C<a>. That is, they first take the subscript, and only thendereference the thing at that subscript. That's fine in C, but this isn't C.The seemingly equivalent construct in Perl, C<$$aref[$i]> first doesthe deref of $aref, making it take $aref as a reference to anarray, and then dereference that, and finally tell you the I<i'th> valueof the array pointed to by $AoA. If you wanted the C notion, you'd have towrite C<${$AoA[$i]}> to force the C<$AoA[$i]> to get evaluated firstbefore the leading C<$> dereferencer.=head1 WHY YOU SHOULD ALWAYS C<use strict>If this is starting to sound scarier than it's worth, relax. Perl hassome features to help you avoid its most common pitfalls. The bestway to avoid getting confused is to start every program like this: #!/usr/bin/perl -w use strict;This way, you'll be forced to declare all your variables with my() andalso disallow accidental "symbolic dereferencing". Therefore if you'd donethis: my $aref = [ [ "fred", "barney", "pebbles", "bambam", "dino", ], [ "homer", "bart", "marge", "maggie", ], [ "george", "jane", "elroy", "judy", ], ]; print $aref[2][2];The compiler would immediately flag that as an error I<at compile time>,because you were accidentally accessing C<@aref>, an undeclaredvariable, and it would thereby remind you to write instead: print $aref->[2][2]=head1 DEBUGGINGX<data structure, debugging> X<complex data structure, debugging>X<AoA, debugging> X<HoA, debugging> X<AoH, debugging> X<HoH, debugging>X<array of arrays, debugging> X<hash of arrays, debugging>X<array of hashes, debugging> X<hash of hashes, debugging>Before version 5.002, the standard Perl debugger didn't do a very nice job ofprinting out complex data structures. With 5.002 or above, thedebugger includes several new features, including command line editing aswell as the C<x> command to dump out complex data structures. Forexample, given the assignment to $AoA above, here's the debugger output: DB<1> x $AoA $AoA = 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'=head1 CODE EXAMPLESPresented with little comment (these will get their own manpages someday)here are short code examples illustrating access of varioustypes of data structures.=head1 ARRAYS OF ARRAYSX<array of arrays> X<AoA>=head2 Declaration of an ARRAY OF ARRAYS @AoA = ( [ "fred", "barney" ], [ "george", "jane", "elroy" ], [ "homer", "marge", "bart" ], );=head2 Generation of an ARRAY OF ARRAYS # reading from file while ( <> ) { push @AoA, [ split ]; } # calling a function for $i ( 1 .. 10 ) { $AoA[$i] = [ somefunc($i) ]; } # using temp vars for $i ( 1 .. 10 ) { @tmp = somefunc($i); $AoA[$i] = [ @tmp ]; } # add to an existing row push @{ $AoA[0] }, "wilma", "betty";=head2 Access and Printing of an ARRAY OF ARRAYS # one element $AoA[0][0] = "Fred"; # another element $AoA[1][1] =~ s/(\w)/\u$1/; # print the whole thing with refs for $aref ( @AoA ) { print "\t [ @$aref ],\n"; } # print the whole thing with indices for $i ( 0 .. $#AoA ) { print "\t [ @{$AoA[$i]} ],\n"; } # print the whole thing one at a time for $i ( 0 .. $#AoA ) { for $j ( 0 .. $#{ $AoA[$i] } ) { print "elt $i $j is $AoA[$i][$j]\n"; } }=head1 HASHES OF ARRAYSX<hash of arrays> X<HoA>=head2 Declaration of a HASH OF ARRAYS %HoA = ( flintstones => [ "fred", "barney" ], jetsons => [ "george", "jane", "elroy" ], simpsons => [ "homer", "marge", "bart" ], );=head2 Generation of a HASH OF ARRAYS # reading from file # flintstones: fred barney wilma dino while ( <> ) { next unless s/^(.*?):\s*//; $HoA{$1} = [ split ]; } # reading from file; more temps # flintstones: fred barney wilma dino while ( $line = <> ) { ($who, $rest) = split /:\s*/, $line, 2; @fields = split ' ', $rest;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -