- #!/usr/bin/perl -w
-
#
-
use strict;
-
-
my %provisions;
-
my $person;
-
-
while(<>){
-
if( /^(\S.*)/){
-
$person = $1;
-
$provisions{$person} = [ ]; #this can be omitted.
-
}elsif(/^\s+(\S.*)/){
-
push @{$provisions{$person}}, $1;
-
}else{
-
die "check $_";
-
}
-
-
}
-
-
for( keys %provisions){
-
print "$_\n";
-
my $r = $provisions{$_};
-
print "@$r, \n";
-
}
the above code will put the containt like:
- The Skipper
-
blue_shirt
-
hat
-
jacket
-
preserver
-
sunscreen
-
Professor
-
sunscreen
-
water_bottle
-
slide_rule
-
Gilligan
-
red_shirt
-
hat
-
lucky_socks
-
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.
A
ny 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.
- my $top;
-
$top->[2]->[4] = 'lee-lou';
最初$top是undef,因为我们像用一个引用一样来解引用$top。所以perl把一个匿名空数组的引用赋给$top.接下来perl去访问第三个元素,这让数组的长度变长为三。这个元素还是个undef,所以perl又赋一个匿名空数组的引用给第三个元素。最后把lee-lou赋给第二次解引用的第五个元素。
阅读(579) | 评论(0) | 转发(0) |