I’ve come across the following line of code. It has issues:
- it is intended to do the same as push
- it ought to have used push
- it’s hard to read, understand
- I’ve since changed it to use push
- it does something I thought was illegal, but clearly isn’t
here it is:
$array [++$#array] = 'data';
My question is: what does it mean to pre-increment $#array? I always considered $#array to be an attribute of an array, and not writable.
perldata says:
‘The length of an array is a scalar value. You may find the length of array @days by evaluating $#days , as in csh. However, this isn’t the length of the array; it’s the subscript of the last element, which is a different value since there is ordinarily a 0th element. Assigning to $#days actually changes the length of the array. Shortening an array this way destroys intervening values. Lengthening an array that was previously shortened does not recover values that were in those elements.’
Modifying $#array is useful in some cases, but in this case, clearly push is better.