How do I make an array shorter in Perl? I read some webpages indicating that I can assign:
$#ARRAY = 42;
I read that the use of $# is deprecated. I need a solution that will work for an array of arrays, too. This didn't work:
$#$ARRAY[$i] = 42;
The size of a Java array is fixed when you allocate it, and cannot be changed. If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.
You can't change the length of an array object once it's created. Here's an excerpt from JLS 10.2. Array Variables: Once an array object is created, its length never changes.
Arrays can either hold primitive values or object values. An ArrayList can only hold object values. You must decide the size of the array when it is constructed. You can't change the size of the array after it's constructed.
Resize<T>(T[], Int32) Method.
I'm not aware of assigning $#ARRAY
being deprecated; perldoc perldata
from 5.10.0 certainly says nothing about it. It is the fastest way to truncate an array.
If you want something a little more readable, use splice
:
splice @ARRAY, 43;
(Note 43
instead of 42
- $#ARRAY
gets you the last index of the array, whereas splice
taks the length of the array instead).
As for working on arrays of arrays, I assume you mean being able to truncate a nested array via a reference? In that case, you want:
$#{$ARRAY->[7]} = 42;
or
splice @{$ARRAY->[7]}, 43;
Your options are near limitless (I've outlined five approaches here) but your strategy will be dictated by exactly what your specific needs and goals are. (all examples will convert @array to have no more than $N elements)
[EDIT]
As others have pointed out, the way suggested in the original question is actually not deprecated, and it provides the fastest, tersest, but not necessarily the most readable solution. It also has the side effect of expanding an array of fewer than $N elements with empty elements:
$#array = $N-1;
Least code:
#best for trimming down large arrays into small arrays
@array = $array[0..($N-1)];
Most efficient for trimming a small number off of a large array:
#This is a little less expensive and clearer
splice(@array, $n, @#array);
Undesirable in almost all cases, unless you really love delete():
#this is the worst solution yet because it requires resizing after the delete
while($N-1 < $#array)
{
delete(array[$i]);
}
Useful if you need the remainder of the list in reverse order:
#this is better than deleting because there is no resize
while($N-1 < $#array)
{
pop @array;
#or, "push $array2, pop @array;" for the reverse order remainder
}
Useful for saving time in long run:
#don't put more values into the array than you actually want
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With