- #!perl
-
use feature qw(say);
-
use strict;
-
my @skipper=qw(blue_shirt hat jacket preserver sunscreen);
-
my @skipper_with_name=('Skipper',\@skipper);
-
my @professor=qw(sunscreen water_bottel slide_rule batteries radio);
-
my @professor_with_name=('Professor',\@professor);
-
my @gilligan=qw(red_shirt hat lucky_socks water_bottle);
-
my @gilligan_with_name=('Gilligan',\@gilligan);
-
my @all_with_names=(\@skipper_with_name,
-
\@professor_with_name,
-
\@gilligan_with_name);
-
say "${$all_with_names[1]}[0]:@{${$all_with_names[1]}[1]}";
可以使用引用实现较为复杂的数据结构,如程序中所示.
可以看到,在第14行,访问嵌套的引用的写法非常的复杂,可读性非常低.
因此需要较为简单明了的嵌套引用的访问方法.
用箭头简化嵌套引用
对于上面的程序,为了取得professor的sunscreen,表达式的写法是
${${$all_with_names[1]}[1]}[0]
$all_with_names[1]:@all_with_names下标为1的元素,@professor_with_name的引用
${$all_with_names[1]}[1]:@professor_with_name下标为1的元素,@professor的引用
${${$all_with_names[1]}[1]}[0]:@professor下标为0的元素,sunscreen.
可以简写为
$all_with_names[1]->[1]->[0]
进一步简写为
$all_with_names[1][1][0]
省略箭头(->)的规则是:
如果箭头(->)被夹在两个下标之间(类似下标的东西),则这个箭头就可以省略.(if the arrow ends up between "subscripty kinds of things",such as square brackets,we can also drop the arrow)
The arrow has to be between non-subscripty things.
- #!perl
-
use feature qw(say);
-
usestrict;
-
my@skipper=qw(blue_shirt hat jacket preserver sunscreen);
-
my @skipper_with_name=('Skipper',\@skipper);
-
my @professor=qw(sunscreen water_bottel slide_rule batteries radio);
-
my @professor_with_name=('Professor',\@professor);
-
my @gilligan=qw(red_shirt hat lucky_socks water_bottle);
-
my @gilligan_with_name=('Gilligan',\@gilligan);
-
my @all_with_names=(\@skipper_with_name,
-
\@professor_with_name,
-
\@gilligan_with_name);
-
my $root=\@all_with_names;
-
$root->[2]->[1]->[0];
-
$root->[2][1][0];
-
$root[2][1][0];
新增加一个@all_with_names的引用$root.
第16,17行的写法都是正确的访问.
第18行,省掉了紧跟在root后的箭头(->),意思变为,root是一个数组的名字(@root),取其中下标为2的元素,这是一个数组的引用...................
然而,root只是一个标量的名字,这就引发了语义和语法错误.