How to push values to an array in Perl

Overview

We can use the Perl push() function to push values to the end of an array.

Syntax

push(Array, values)
Syntax of push() method in Perl

Parameters

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

values: This is the value(s) we want to push to the array Array.

Return value

The value returned is the number of elements in the newly modified array.

Example

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

Explanation

  • Line 2: We create an array gnaam.
  • Line 3: We print its values before pushing some values to it with the push() method.
  • Line 6: We call the push() method to add elements to the array we created previously.
  • Line 7: We print the the newly modified array.

Free Resources