📄 perldsc.1
字号:
.\" Automatically generated by Pod::Man 2.16 (Pod::Simple 3.05).\".\" Standard preamble:.\" ========================================================================.de Sh \" Subsection heading.br.if t .Sp.ne 5.PP\fB\\$1\fR.PP...de Sp \" Vertical space (when we can't use .PP).if t .sp .5v.if n .sp...de Vb \" Begin verbatim text.ft CW.nf.ne \\$1...de Ve \" End verbatim text.ft R.fi...\" Set up some character translations and predefined strings. \*(-- will.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left.\" double quote, and \*(R" will give a right double quote. \*(C+ will.\" give a nicer C++. Capital omega is used to do unbreakable dashes and.\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff,.\" nothing in troff, for use with C<>..tr \(*W-.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'.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" "". ds C` "". ds C' ""'br\}.el\{\. ds -- \|\(em\|. ds PI \(*p. ds L" ``. ds R" '''br\}.\".\" Escape single quotes in literal strings from groff's Unicode transform..ie \n(.g .ds Aq \(aq.el .ds Aq '.\".\" If the F register is turned on, we'll generate index entries on stderr for.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index.\" entries marked with X<> in POD. Of course, you'll have to process the.\" output yourself in some meaningful fashion..ie \nF \{\. de IX. tm Index:\\$1\t\\n%\t"\\$2"... nr % 0. rr F.\}.el \{\. de IX...\}.\".\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2)..\" Fear. Run. Save yourself. No user-serviceable parts.. \" 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 /.\}.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 / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'.\}. \" 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 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. \" 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 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.\}.rm #[ #] #H #V #F C.\" ========================================================================.\".IX Title "PERLDSC 1".TH PERLDSC 1 "2007-12-18" "perl v5.10.0" "Perl Programmers Reference Guide".\" For nroff, turn off justification. Always turn off hyphenation; it makes.\" way too many mistakes in technical documents..if n .ad l.nh.SH "NAME"perldsc \- Perl Data Structures Cookbook.IX Xref "data structure complex data structure struct".SH "DESCRIPTION".IX Header "DESCRIPTION"The 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 \f(CW$m{$AoA,$b}\fR notation borrowed from \fBawk\fR in which thekeys are actually more like a single concatenated string \f(CW"$AoA$b"\fR, 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..PPThe 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!.PP.Vb 8\& for $x (1 .. 10) {\& for $y (1 .. 10) {\& for $z (1 .. 10) {\& $AoA[$x][$y][$z] =\& $x ** $y + $z;\& }\& }\& }.Ve.PPAlas, however simple this may appear, underneath it's a much moreelaborate construct than meets the eye!.PPHow do you print it out? Why can't you say just \f(CW\*(C`print @AoA\*(C'\fR? 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?.PPAs 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..PPThis 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..PPLet's look at each of these possible constructs in detail. There are separatesections on each of the following:.IP "\(bu" 5arrays of arrays.IP "\(bu" 5hashes of arrays.IP "\(bu" 5arrays of hashes.IP "\(bu" 5hashes of hashes.IP "\(bu" 5more elaborate constructs.PPBut for now, let's look at general issues common to allthese types of data structures..SH "REFERENCES".IX Xref "reference dereference dereferencing pointer".IX Header "REFERENCES"The most important thing to understand about all data structures in Perl\&\*(-- including multidimensional arrays\*(--is that even though they mightappear otherwise, Perl \f(CW@ARRAY\fRs and \f(CW%HASH\fRes 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 \fIreferences\fR to other arrays or hashes..IX Xref "multidimensional array array, multidimensional".PPYou 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..PPYou can (and should) read more about references in the \fIperlref\fR\|(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 \fIuse\fR it as though it were atwo-dimensional one. This is actually the way almost all Cmultidimensional arrays work as well..PP.Vb 4\& $array[7][12] # array of arrays\& $array[7]{string} # array of hashes\& $hash{string}[7] # hash of arrays\& $hash{string}{\*(Aqanother string\*(Aq} # hash of hashes.Ve.PPNow, because the top level contains only references, if you try to printout your array in with a simple \fIprint()\fR function, you'll get somethingthat doesn't look very nice, like this:.PP.Vb 5\& @AoA = ( [2, 3], [4, 5, 7], [0] );\& print $AoA[1][2];\& 7\& print @AoA;\& ARRAY(0x83c38)ARRAY(0x8b194)ARRAY(0x8b1d0).Ve.PPThat'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, like\&\f(CW\*(C`${$blah}\*(C'\fR, \f(CW\*(C`@{$blah}\*(C'\fR, \f(CW\*(C`@{$blah[$i]}\*(C'\fR, or else postfix pointer arrows,like \f(CW\*(C`$a\->[3]\*(C'\fR, \f(CW\*(C`$h\->{fred}\*(C'\fR, or even \f(CW\*(C`$ob\->method()\->[3]\*(C'\fR..SH "COMMON MISTAKES".IX Header "COMMON MISTAKES"The 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:.PP.Vb 4\& for $i (1..10) {\& @array = somefunc($i);\& $AoA[$i] = @array; # WRONG!\& }.Ve.PPThat'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:.PP.Vb 4\& for $i (1..10) {\& @array = somefunc($i);\& $counts[$i] = scalar @array;\& }.Ve.PPHere's the case of taking a reference to the same memory locationagain and again:.PP.Vb 4\& for $i (1..10) {\& @array = somefunc($i);\& $AoA[$i] = \e@array; # WRONG!\& }.Ve.PPSo, 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!.PPUnfortunately, while this is true, it's still broken. All the referencesin \f(CW@AoA\fR refer to the \fIvery same place\fR, and they will therefore all holdwhatever was last in \f(CW@array\fR! It's similar to the problem demonstrated inthe following C program:.PP.Vb 5\& #include <pwd.h>\& main() {\& struct passwd *getpwnam(), *rp, *dp;\& rp = getpwnam("root");\& dp = getpwnam("daemon");\&\& printf("daemon name is %s\enroot name is %s\en",\& dp\->pw_name, rp\->pw_name);\& }.Ve.PPWhich will print.PP.Vb 2\& daemon name is daemon\& root name is daemon.Ve.PPThe problem is that both \f(CW\*(C`rp\*(C'\fR and \f(CW\*(C`dp\*(C'\fR are pointers to the same locationin memory! In C, you'd have to remember to \fImalloc()\fR yourself some newmemory. In Perl, you'll want to use the array constructor \f(CW\*(C`[]\*(C'\fR or thehash constructor \f(CW\*(C`{}\*(C'\fR instead. Here's the right way to do the precedingbroken code fragments:.IX Xref "[] {}".PP.Vb 4\& for $i (1..10) {\& @array = somefunc($i);\& $AoA[$i] = [ @array ];\& }.Ve.PPThe square brackets make a reference to a new array with a \fIcopy\fRof what's in \f(CW@array\fR at the time of the assignment. This is whatyou want..PPNote that this will produce something similar, but it'smuch harder to read:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -