If you don't care about mutations (implied by the self-referential lhs @foo
= something referencing @foo
) use the two-argument splice()
, see perldoc -f splice for more info.
splice ARRAY,OFFSET
Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, returns the elements removed from the array. In scalar context, returns the last element removed, or "undef" if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array, perl issues a warning, and splices at the end of the array.
Then watch the effect:
@_ = 1..10;
splice @_, 5;
say for @_;
@_ = 1..3;
splice @_, 5;
say for @_;
If you're using warnings
, and I hope you'll have to check for the length (as in Axeman's suggestion) or disable the noisy warning (splice() offset past end of array):
{
no warnings 'misc';
splice @_, 5;
}