How to unshift elements to the beginning of an array in Perl?

Question

How to unshift elements to the beginning of an array in Perl?

How to Unshift Elements to the Beginning of an Array in Perl?

In Perl, adding one or more elements to the beginning of an array is commonly done using the unshift function. This operation inserts the new elements at the front, shifting all existing elements to the right to accommodate them.

Syntax:

unshift @array, LIST;

Here, @array is the array you want to modify, and LIST can be one or more scalar values. The unshift function returns the new number of elements in the array after the operation.

Key Perl Concepts

  • unshift changes the original array in place.
  • Perl arrays use the @ sigil to refer to the entire array (e.g., @array), while individual elements use $array[index].
  • Perl's "There's more than one way to do it" (TMTOWTDI) philosophy means you could also combine arrays or use other methods, but unshift is the most straightforward and idiomatic for this.

Example: Using unshift

#!/usr/bin/perl
use strict;
use warnings;

my @fruits = ('apple', 'banana', 'cherry');

print "Original array: @fruits\n";

# Add 'orange' and 'grape' to the beginning
my $new_length = unshift @fruits, 'orange', 'grape';

print "After unshift: @fruits\n";
print "New array length: $new_length\n";

Expected output:

Original array: apple banana cherry
After unshift: orange grape apple banana cherry
New array length: 5

Version Notes and Gotchas

  • The unshift function is standard since early Perl versions, so it works consistently across Perl 5.x.
  • unshift accepts a list of elements, not an array reference. If you have an array reference, dereference it first: unshift @array, @{$aref}.
  • Remember the difference between push and unshiftpush appends elements at the end, unshift prepends them.
  • Be careful not to mix scalar and list context unintentionally; unshift returns the new array length in scalar context, not the modified array itself.

In summary, unshift is the easy and efficient way to add elements to the start of an array in Perl, helping you manipulate lists with minimal fuss.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 4ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions