There are two ways of interpreting the question.
- How to reduce the length of the array?
- How to reduce the amount of memory consumed by the array?
Most of the answers so far focus on the former. In my view, the best answer to that is the splice function. For example, to remove 10 elements from the end:
splice @array, -10;
However, because of how Perl manages memory for arrays, the only way to ensure that an array takes less memory is to copy it to a new array (and let the memory of the old array be reclaimed). For this, I would tend to think about using a slice operation. E.g., to remove 10 elements:
@new = @old[ 0 .. $#old - 10 ]
Here's a comparison of different approaches for a 500 element array (using 2104 bytes):
original: length 500 => size 2104
pound: length 490 => size 2208
splice: length 490 => size 2104
delete: length 490 => size 2104
slice: length 490 => size 2064
You can see that only the slice operation (copied to a new array) has a smaller size than the original.
Here's the code I used for this analysis:
use strict;
use warnings;
use 5.010;
use Devel::Size qw/size/;
my @original = (1 .. 500);
show( 'original', \@original );
my @pound = @original;
$#pound = $#pound - 10;
show( 'pound', \@pound );
my @splice = @original;
splice(@splice,-10);
show( 'splice', \@splice);
my @delete = @original;
delete @delete[ -10 .. -1 ];
show( 'delete', \@delete );
my @slice = @original[0 .. $#original - 10];
show( 'slice', \@slice);
sub show {
my ($name, $ref) = @_;
printf( "%10s: length %4d => size %d\n", $name, scalar @$ref, size($ref));
}