要访问数组元素,@和$均起作用。例如:
@item_price_list = (5 , 8 , 24);
@item_name_list = ("Apple", "Banana", "Mushroom");
print "The price of one @item_name_list[1] is @item_price_list[1] gold coins.\n";
print "The price of one $item_name_list[1] is $item_price_list[1] gold coins.\n";
在我看来,这种语法是不规则的:$
用于定义标量,但也可以用于引用数组。在bash中,当我们要引用变量时,我们在变量之前使用$
,并且$
不被视为变量名称的一部分,但是在每个变量中,$
被视为标量的一部分变量。 @
是否不被视为perl中数组名称的一部分?
答案 0 :(得分:3)
数组上的前导符号(“ $”或“ @”)指示您要返回的是奇异值(标量)还是复数(列表)。列表是否由一个元素组成,如
@item_price_list[1]
或多个
中的元素@item_price_list[0..2]
列表与数组的主要区别在于,标量上下文中的列表返回列表的最后一个元素,而数组将返回列表中的元素数量。
因此添加
print "The price of one @item_name_list[1] is " . @item_price_list[0..2] . " gold coins.\n";
会产生
The price of one Banana is 24 gold coins.
同时
print "The price of one @item_name_list[1] is " . @item_price_list . " gold coins.\n";
会产生
The price of one Banana is 3 gold coins.