push, pop, shift and splice
| push, pop, shift, unshift | |
| splice | |
| reverse | |
| A queue and a stack |
push, pop, shift, unshift
Four functions work the two ends of a list. push and pop use the right end, unshift and shift use the left end. All four change the array in place: pop and shift return the element they removed, while push and unshift return the new number of elements.
my @jobs = ("build");
push @jobs, "test"; # build test
unshift @jobs, "fetch"; # fetch build test
my $last = pop @jobs; # test, gone from the list
my $first = shift @jobs; # fetch, gone from the list
print "@jobs\n"; # build
perl demo.pl
build
Both pop and shift return undef on an empty array. Guard a loop with while (@jobs) rather than testing the returned value, or the last element may be a legitimate zero or empty string.
splice
splice is the general scissors: give it an array, a start offset, a length, and optionally the list that replaces the removed elements. It returns whatever it cut out.
my @nums = (1, 2, 3, 4, 5);
my @cut = splice @nums, 1, 2; # cuts 2 3
print "@cut / @nums\n"; # 2 3 / 1 4 5
splice @nums, 1, 0, "new"; # inserts at offset 1
print "@nums\n"; # 1 new 4 5
perl demo.pl
2 3 / 1 4 5
1 new 4 5
A length of zero inserts without removing anything, and omitting the length removes everything to the end. Those two forms cover insert and truncate, so you rarely need a second function.
reverse
reverse returns the list in the opposite order without touching the original. In scalar context it reverses the characters of a string instead, which is a useful reminder that context decides behavior.
my @words = qw(one two three);
my @back = reverse @words;
print "@back\n"; # three two one
print scalar reverse("abc"), "\n"; # cba
perl demo.pl
three two one
cba
A queue and a stack
The four end functions give you the two classic data structures for free. push and pop make a stack: the last item added is the first one out. push and shift make a queue: first in, first out.
my @stack = ();
push @stack, $_ for qw(a b c);
print pop(@stack), "\n" while @stack; # c, then b, then a
perl demo.pl
c
b
a
For big queues shift is slow, because every remaining element moves down one slot. Lesson 48 shows the index-based alternative.
Next: Hashes
Article author: Arthur Isaev