How to shift elements from the beginning of an array in Perl?
Question
How to shift elements from the beginning of an array in Perl?
In Perl, the shift function is the standard and simplest way to remove (or "shift") elements from the beginning of an array. It removes the first element of the array, reduces the array size by one, and returns the removed element. This is often used when processing queues or streams of data where you want to consume elements from the front.
How shift Works
When you use shift @array, Perl does the following:
- Removes the first element (
$array[0]) from the array. - Moves all other elements one position to the left (indexes decrease by 1).
- Returns the removed element.
- Reduces the array’s length by one.
It’s important to note that shift acts in scalar context by default, returning a single element — the first one.
Basic Example
#!/usr/bin/perl
use strict;
use warnings;
my @queue = ('apple', 'banana', 'cherry');
# Shift (remove) the first item
my $first = shift @queue;
print "Shifted element: $first\n";
print "Remaining elements: @queue\n";
This code outputs:
Shifted element: apple
Remaining elements: banana cherry
Multiple shifts
If you want to remove multiple elements from the start, you can call shift repeatedly (e.g., in a loop), or use an array slice or splice. Perl doesn't have a built-in shift variant that returns multiple elements at once.
Perl-Specific Notes
- The
shiftfunction is versatile; when used without arguments inside a subroutine, it shifts from@_. - The sigil
@denotes an array, so@arrayrefers to the whole list, butshift @arrayreturns a scalar (first element), asshiftreturns a scalar element. - Because
shiftphysically modifies the array, be aware it affects subsequent array operations.
Common Pitfalls
- If the array is empty,
shiftreturnsundef, so check for that if you rely on the return value. - Do not confuse
shiftwithpop, which removes an element from the end. - Using
shifton a large array repeatedly can be inefficient because it moves all elements each time. For large queues, consider other data structures or modules.
Summary
To shift elements from the beginning of an array in Perl, use the shift function. It removes and returns the first element, modifying the array in-place. This is a core, idiomatic way to process arrays as queues.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 7ms
Shifted element: apple
Remaining elements: banana cherry
(empty)