Array Functions
Perl arrays grow and shrink on demand. A handful of built-in functions let you use an array as a stack, a queue, or a general-purpose list.
push, pop, shift, unshift
| Function | Works on | Effect | Returns |
|---|---|---|---|
push @a, LIST |
end | adds elements | new length |
pop @a |
end | removes the last element | that element |
unshift @a, LIST |
start | adds elements | new length |
shift @a |
start | removes the first element | that element |
use strict;
use warnings;
my @stack = ();
push @stack, "page1";
push @stack, "page2", "page3";
print "History: @stack\n";
my $back = pop @stack;
print "Back from: $back, now: @stack\n";
my @line = qw(customer2 customer3);
unshift @line, "customer1";
my $served = shift @line;
print "Served $served, waiting: @line\n";History: page1 page2 page3
Back from: page3, now: page1 page2
Served customer1, waiting: customer2 customer3
push + pop give you a stack (last in, first out); push + shift give you a queue (first in, first out). pop and shift return undef when the array is empty, which makes them convenient loop conditions.
splice: the Swiss army knife
splice @array, OFFSET, LENGTH, LIST removes LENGTH elements starting at OFFSET, inserts LIST in their place, and returns the removed elements:
use strict;
use warnings;
my @playlist = qw(intro verse chorus verse outro);
my @removed = splice @playlist, 1, 2; # remove 2 items at index 1
print "Removed: @removed | Left: @playlist\n";
splice @playlist, 1, 0, "bridge", "solo"; # insert without removing
print "Inserted: @playlist\n";
splice @playlist, -1, 1, "finale"; # replace the last one
print "Replaced: @playlist\n";Removed: verse chorus | Left: intro verse outro
Inserted: intro bridge solo verse outro
Replaced: intro bridge solo verse finale
reverse and sort
reverse returns the list in the opposite order. sort returns it sorted; by default it compares as strings, which surprises people with numbers:
use strict;
use warnings;
my @names = qw(zoe adam mia ben);
my @nums = (10, 9, 100, 1);
print "Reversed: ", join(" ", reverse @names), "\n";
print "Sorted: ", join(" ", sort @names), "\n";
print "String sort of numbers: ", join(" ", sort @nums), "\n";
print "Numeric sort: ", join(" ", sort { $a <=> $b } @nums), "\n";
print "Descending: ", join(" ", sort { $b <=> $a } @nums), "\n";Reversed: ben mia adam zoe
Sorted: adam ben mia zoe
String sort of numbers: 1 10 100 9
Numeric sort: 1 9 10 100
Descending: 100 10 9 1
The block { $b <=> $a } swaps the two operands, so the largest number comes first. Neither sort nor reverse changes the original array; they return new lists. To sort in place, assign back: @nums = sort { $a <=> $b } @nums;. The sorting lesson explains comparator blocks in depth.
join and List::Util
join glues a list into one string, and the core module List::Util adds many everyday helpers:
use strict;
use warnings;
use List::Util qw(sum max min first uniq shuffle);
my @scores = (72, 95, 88, 95, 61);
print "Joined: ", join(", ", @scores), "\n";
print "Sum: ", sum(@scores), "\n";
print "Max: ", max(@scores), ", min: ", min(@scores), "\n";
print "First above 90: ", first { $_ > 90 } @scores;
print "\n";
print "Unique: ", join(" ", uniq @scores), "\n";Joined: 72, 95, 88, 95, 61
Sum: 411
Max: 95, min: 61
First above 90: 95
Unique: 72 95 88 61
Checking membership
Arrays have no built-in "contains" function. The idiomatic test uses grep (next lesson) or List::Util's any:
use strict;
use warnings;
use List::Util qw(any none);
my @admins = qw(root alice);
my $user = "alice";
print "$user is an admin\n" if any { $_ eq $user } @admins;
print "bob is not an admin\n" if none { $_ eq "bob" } @admins;alice is an admin
bob is not an admin
Tip: If you test membership often, store the items as keys of a hash instead: lookups become instant. See the hashes lesson.
Test yourself
Which function removes and returns the FIRST element of an array?
popshiftunshiftsplice @a, -1
What does sort (10, 9, 2) return?
(2, 9, 10)(10, 2, 9)(10, 9, 2)(9, 10, 2)
What does splice @a, 1, 0, 'x' do?
- Removes element 1
- Inserts
'x'at index 1 without removing anything - Replaces element 0 with
'x' - Empties the array