Trusted answers to developer questions

How to use the unshift() function of an Array in Perl

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

The unshift() function in Perl prepends elements to the beginning of an array in Perl.

Syntax

unshift(Array, values)
Syntax for unshift() method in Perl

Parameters

Array: This is the array we want to prepend some values to.

values: These are the values or a value we want to prepend to the Array array.

Return value

It returns the number of elements in the array.

Code example

# create an array
@gnaam = ("Apple","Amazon", "Meta");
print "Before push: \@coins = @gnaam\n";
# push values to the array
print "After push: Number of elemets in \@gnaam =" , unshift(@gnaam, "Google","Netflix");
print "\nAfter push: \@gnaam = @gnaam";

Explanation

  • Line 2: We create an array called gnaam.
  • Line 3: We print its values before prepending some values onto it with the unshift() method.
  • Line 6: We call the unshift() method to add elements to the array. Then, we print the number of elements using the print statement.
  • Line 7: We print the newly modified array.

RELATED TAGS

perl
unshift
array
Did you find this helpful?