Chinaunix首页 | 论坛 | 博客
  • 博客访问: 7771058
  • 博文数量: 701
  • 博客积分: 2150
  • 博客等级: 上尉
  • 技术积分: 13233
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-29 16:28
个人简介

天行健,君子以自强不息!

文章分类

全部博文(701)

文章存档

2019年(2)

2018年(12)

2017年(76)

2016年(120)

2015年(178)

2014年(129)

2013年(123)

2012年(61)

分类: PERL

2013-04-02 12:29:12

Perl Data Structures Cookbook
Perl数据结构百科

一、描述
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 $m{$AoA,$b} notation borrowed from awk in which 
the keys are actually more like a single concatenated string "$AoA$b" , 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.
在Perl 5.0之前,Perl最缺的功能是构建复杂的数据结构。
虽然没有直接的语言支持,但一些NB的程序员也有办法仿造生成,不过很难有效工作。
即使有时使用awk语言来生成$m{$AoA, $}这样的结构体,但它很像是拼接后的字符串"$AoA$b"。
而且遍历和排序也很困难。
更疯狂的程序甚至直接hack Perl的内部符号表,当然这个更难搞。


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 an array with three dimensions!
5.0版本后,Perl提供了复杂数据结构的支持,写出像下面的三维数组就很容易了。
    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 more elaborate construct  than meets the eye!
当然,表面简单的下面是复杂的构成。


How do you print it out? Why can't you say just print @AoA ? How do you sort it? How can 
you pass it to a function or get one of these back from a function? Is it 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?
如何打印输出?
为什么可用print @AoA?
如何排序?

如何传给函数或从函数返回?
这是对象吗?
如何保存并读取?
如何访问整个行列?

它的值都是数字的吗?


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.
问题是很多,更现实的问题是缺少给初学者的文档。


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.
本文提供了很多的数据结构的细节实现,可以把它当做百科书一样查找和直接用到程序开中。


Let's look at each of these possible constructs in detail. There are separate sections on 
each of the following:
分类如下: 
  arrays of arrays;                  数组的元素为数组
  hashes of arrays;                 哈希表的元素为数组
  arrays of hashes;                 数组的元素为哈希表
  hashes of hashes                  哈希表的元素为哈希表
  more elaborate constructs   更复杂的结构
But for now, let's look at general issues common to all these types of data structures.
在这之前,先来看看对来这些数据结构类型来说的一些更一般性的问题。


二、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 @ARRAY s 
and %HASH es 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 references to other arrays or hashes.
要理解Perl中所有数据结构--包括多维数据--最重要的一点是: 
  @ARRAY s 和 %HASH es 在内部的表示都是一维;
  且它们只能存储标题值(如字符串,数字,或引用);
  它们不能直接以数组或哈希表作为元素,但可以通过引用来实现

You can't use a reference to an 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.
不能对真正的哈希和数组使用相同的引用。
这一点,和对于C或C++程序员来说,不区分数组和指针的一样的,都会造成混淆。

You can (and should) read more about references in perlref. 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 use it as though it were a two-dimensional 
one. This is actually the way almost all C multidimensional arrays work as well.
总体来说,引用类似于指针。
这就意味着,当访问二维或多维数组/哈希时,实际上访问的是一个元素为引用的一维对象。
这一点和C也是类似的。
    $array[7][12];                 # array of arrays
    $array[7]{string};           # array of hashes 数组的元素为哈希
    $hash{string}[7];            # hash of arrays  哈希的元素为数组
    $hash{string}{'another string'} # hash of hashes

Now, because the top level contains only references, if you try to print out your array 
in with a simple print() function, you'll get something that 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 have to do this yourself using either 
prefix typing indicators, like ${$blah} , @{$blah} , @{$blah[$i]} , or else postfix pointer 
arrows, like $a->[3] , $h->{fred} , or even $ob->method()->[3] .
Perl并不会隐示地对变量进行去引用。
要去这些引用,必须自己使用前缀或后缀符来去掉。

三、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:
构建像数组的数组这样的结构最常见的错误是:
  意外地计算了元素的个数;
  对相同的内存区域重复地使用同一个引用。
下面的例子是对嵌套数组赋值的错误使用:
    foreach $i (1..10) {
       @array = somefunc($i);
       $AoA[$i] = @array;           # WRONG!
    }

That's just the simple case of assigning an array 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:
正确的方法应该是:
    foreach $i (1..10) {
       @array = somefunc($i);
       $counts[$i] = scalar @array;
    }


Here's the case of taking a reference to the same memory location again and again:
下面的错误用法是: 对同一个内存区进行重复引用.
    foreach $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 by golly, you've made me one!
Unfortunately, while this is true, it's still broken. All the references in @AoA 
refer to the very same place, and they will therefore all hold whatever was last 
in @array! It's similar to the problem demonstrated in the following C program:
像上面的问题,在C语言中也有类似的情况:

    #include
    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 daemon

The problem is that both rp and dp are pointers to the same location in memory! 
In C, you'd have to remember to malloc() yourself some new memory. In Perl, you'll 
want to use the array constructor [] or the hash constructor {} instead. Here's 
the right way to do the preceding broken code fragments:
在C中,会隐式地进行自动的内存分配。
在Perl中,则要显式地使用数组构建符[]  或 哈希构建符{} 来分配新的内存。
下面的正确的方式:
    for $i (1..10) {
       @array = somefunc($i);
       $AoA[$i] = [ @array ];
    }

The square brackets make a reference to a new array with a copy of what's in @array 
at the time of the assignment. This is what you want.
Note that this will produce something similar, but it's much 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 difference is that when you 
assign something in square brackets, you know for sure it's always a brand new reference 
with a new copy of the data. Something else could be going on in this new case with 
the @{$AoA[$i]} dereference on the left-hand-side of the assignment. It all depends on 
whether $AoA[$i] had been undefined to start with, or whether it already contained a 
reference. If you had already populated @AoA with references, as in
这两种方式有一些细微的差别: 
   当使用方括号时,总是会生成一个数据的新的拷贝的引用。
   如果使用@{$AoA[$i]}方式,则当@AoA 包含有一个引用时,如下所示:
    $AoA[3] = \@another_array;

Then the assignment with the indirection on the left-hand-side would use the existing 
reference that was already there:
则会对当前存在的引用使用间接分配。
    @{$AoA[3]} = @array;

Of course, this would have the "interesting" effect of clobbering @another_array. (Have 
you ever noticed how when a programmer says something 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 [] or {} , and you'll 
be fine, although it's not always optimally efficient.
反正,最好还是用[]和{}。

Surprisingly, the following dangerous-looking construct will actually 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 a compile-time declaration 
per se. This means that the my() variable is remade afresh each time through the loop. 
So even though it looks 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 [] and {} instead of relying upon lexical (or 
dynamic) scoping and hidden reference-counting to do 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

四、CAVEAT ON PRECEDENCE【预先警告】
Speaking of things like @{$AoA[$i]} , the following are actually the same thing:
    $aref->[2][2]           # clear
    $$aref[2][2]            # confusing
That's because Perl's precedence rules on its five prefix dereferencers (which look like 
someone swearing: $ @ * % & ) 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 *a[i] to mean what's pointed to by the i'th element of a . 
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.


The seemingly equivalent construct in Perl, $$aref[$i] first does the deref of $aref, 
making it take $aref as a reference to an array, and then dereference that, and finally
 tell you the i'th value of the array pointed to by $AoA. If you wanted the C notion, 
you'd have to write ${$AoA[$i]} to force the $AoA[$i] to get evaluated first before the 
leading $ dereferencer.

五、WHY YOU SHOULD ALWAYS【为什么总是】 use strict
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:
能帮你进行编译检查,从而避免很多程序问题:
    #!/usr/bin/perl -w
    use strict;

This way, you'll be forced to declare all your variables with my() and also disallow 
accidental "symbolic dereferencing". Therefore if you'd done this:
    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 at compile time, because you were 
accidentally accessing @aref , an undeclared variable, and it would thereby remind you 
to write instead:
    print $aref->[2][2]

六、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 x command to dump out complex data structures. 
For example, given the assignment to $AoA above, here's the debugger output:
新的调试器对数组输出很方便:
    DB 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'


阅读(1932) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~