数组 – 赋值中的Perl“上下文”

前端之家收集整理的这篇文章主要介绍了数组 – 赋值中的Perl“上下文”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
作为Perl的新手,我只是不明白以下结果背后是什么样的哲学:

$cnt1 = @arr;           
# this gives the length of the array 'arr'
$cnt2 = @arr[ @indices_arr ];          
# this gives the last element of the @arr[ @indices_arr ];

有人能解释两者之间的区别吗?

解决方法

perldoc perldata开始:

Assignment to a scalar evaluates the right-hand side in scalar context…

和:

If you evaluate an array in scalar context,it returns the length of the array.

和:

Slices in scalar context return the last item of the slice.

@arr是一个数组; @arr [@indices_arr]是一个数组切片.

至于背后的哲学:列表和数组在Perl中是不同的数据类型,具有不同的行为(不要被切片中使用的@sigil抛出,切片是列表,而不是数组).有关两者之间差异的深入解释,请参见Arrays vs. Lists in Perl: What’s the Difference? .

猜你在找的Perl相关文章