How to push elements onto an array in Perl?

Question

How to push elements onto an array in Perl?

How to Push Elements Onto an Array in Perl

In Perl, push is the standard function to append elements to the end of an array. It modifies the array in place and returns the new total number of elements. Arrays are prefixed with @, while individual elements use $. When pushing multiple elements, separate them with commas.

Here is a complete example demonstrating how to use push properly. It prints the array before and after the push operations to clearly show the results.

Using push to Add Elements

use strict;
use warnings;

my @array = ('apple', 'banana');
print "Initial array: @array\n";

# Push one element
push @array, 'cherry';
print "After pushing one element: @array\n";

# Push multiple elements
push @array, ('date', 'elderberry');
print "After pushing multiple elements: @array\n";

# Capture the length after push
my $length = push @array, 'fig';
print "Length after pushing 'fig': $length\n";
print "Final array contents: @array\n";

Key Perl Concepts

  • Sigils: Use @ for arrays (@array), and $ for scalars ($element or $array[0]).
  • push takes an array and a list of scalars to append.
  • It returns the total number of elements in the array after pushing.
  • Perl’s flexibility (TMTOWTDI) means there are other ways to add elements, but push is idiomatic and clear.

Common Pitfalls

  • Always use commas between elements: push @arr, 'a', 'b', not push @arr 'a' 'b'.
  • Ensure you are pushing to an array variable (@array), not a scalar.
  • Remember push does not return the array itself, but its size.

Version Notes

push has been consistent across Perl 5 versions (including 5.10+).

In short, push is the simplest, most efficient way to add new elements to the end of arrays in Perl.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Initial array: apple banana
After pushing one element: apple banana cherry
After pushing multiple elements: apple banana cherry date elderberry
Length after pushing 'fig': 6
Final array contents: apple banana cherry date elderberry fig
STDERR
(empty)

Was this helpful?

Related Questions