I have an array reference that I would like to slice the last two elements of the array. I found that using -2..-1
would work. I was using the following syntax:
subroutine($var->[-2..-1]);
This gave me the following error:
Use of uninitialized value $. in range (or flip)
Argument "" isn't numeric in array element
I changed the line to this and that worked:
subroutine(@$var[-2..-1]);
I don't understand why the second way works though and the first doesn't. I thought using the array operator was the same as dereferencing with @
. Is the context ambiguous with the arrow operator?
CodePudding user response:
->
is the dereference operator. $aref->[$i]
is to an $aref like $arr[$i]
is to @arr
. To get a slice from an array, you need to change the sigil: @arr[$i, $j]
. It's similar for dereference, but instead of changing the sigil, you first dereference the reference, then slice it:
@{ $aref }[$i, $j]
which can be shortened to @$aref[$i, $j]
.
So the ->
operator can only be used for single values for array and hash references. You need @{}
for slices.