Chinaunix首页 | 论坛 | 博客
  • 博客访问: 829779
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-10-21 14:13:19

  1. #!/usr/bin/perl -w
  2. #
  3. use strict;

  4. my %provisions;
  5. my $person;

  6. while(<>){
  7.     if( /^(\S.*)/){
  8.         $person = $1;
  9.         $provisions{$person} = [ ]; #this can be omitted.
  10.     }elsif(/^\s+(\S.*)/){
  11.         push @{$provisions{$person}}, $1;
  12.     }else{
  13.         die "check $_";
  14.     }

  15. }

  16. for( keys %provisions){
  17.     print "$_\n";
  18.     my $r = $provisions{$_};
  19.     print "@$r, \n";
  20. }
the above code will put the containt like:
  1. The Skipper
  2.   blue_shirt
  3.   hat
  4.   jacket
  5.   preserver
  6.   sunscreen
  7. Professor
  8.   sunscreen
  9.   water_bottle
  10.   slide_rule
  11. Gilligan
  12.   red_shirt
  13.   hat
  14.   lucky_socks
  15.   water_bottle
in hash. if the value of a hash is array, we cannot put the array directly to the value but give the reference of the array.

上述code中,可以把 $provisions{$person} = [ ];删除。当调用
push @{ $provisions{'The Skipper'} }, "blue_shirt"; 时,$provisions{"The Skipper"} 是不存在的。这时perl会自动的插入一个reference赋给它。这个reference指向一个匿名空数组。然后再继续push动作。This process is called autovivification.

Any nonexistent variable, or a variable containing undef, which we dereference while looking for a variable location (technically called an lvalue context), is automatically stuffed with the appropriate reference to an empty item, and Perl allows the operation to proceed.

  1. my $top;
  2. $top->[2]->[4] = 'lee-lou';
最初$top是undef,因为我们像用一个引用一样来解引用$top。所以perl把一个匿名空数组的引用赋给$top.接下来perl去访问第三个元素,这让数组的长度变长为三。这个元素还是个undef,所以perl又赋一个匿名空数组的引用给第三个元素。最后把lee-lou赋给第二次解引用的第五个元素。

阅读(530) | 评论(0) | 转发(0) |
0

上一篇:anonymous array and hash

下一篇:hash in hash

给主人留下些什么吧!~~