← Back to Perl Course | Chapter 2: Variables | Lesson 4 of 7

Array functions

Built-in functions add, remove, slice and reorder array elements.

In this page:

  1. Array functions

Array functions

push and pop work on the end of an array, while unshift and shift work on the front. splice removes or inserts elements anywhere, and an array slice such as @a[1,2] picks several elements at once. sort, reverse and join work with whole lists, and map and grep transform or filter them.

Note: sort compares as strings by default; use sort { $a <=> $b } for numeric order.

Example: Array functions

perl
use strict;
use warnings;

my @nums = (5, 3, 10);
push @nums, 7;
unshift @nums, 1;
print "after push and unshift: @nums\n";
my $last  = pop @nums;
my $first = shift @nums;
print "popped $last, shifted $first, left: @nums\n";
print "default sort: ", join(",", sort (10, 9, 100, 1)), "\n";
print "numeric sort: ", join(",", sort { $a <=> $b } (10, 9, 100, 1)), "\n";
splice(@nums, 1, 1, 'x', 'y');
print "after splice: @nums\n";
print "slice: @nums[0,1]\n";
print "doubled: ", join(" ", map { $_ * 2 } grep { /^\d+$/ } @nums), "\n";
print "reversed: ", join(" ", reverse @nums), "\n";

# Output:
# after push and unshift: 1 5 3 10 7
# popped 7, shifted 1, left: 5 3 10
# default sort: 1,10,100,9
# numeric sort: 1,9,10,100
# after splice: 5 x y 10
# slice: 5 x
# doubled: 10 20
# reversed: 10 y x 5
Common Mistakes
  1. Sorting numbers without a numeric comparison block
  2. Forgetting that shift and pop change the array
  3. Mixing up push (end) and unshift (front)
Chapter Summary
  • push/pop work on the end
  • unshift/shift work on the front
  • splice inserts or removes in the middle
  • sort { $a <=> $b } sorts numerically
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.