push, pop, shift and splice

Contents
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

Related articles
Perl
Perl course: zero to hero in 50 lessons
What is Perl and where it runs
Install Perl and check the version
Your first Perl script
The debugger as a REPL
Scalars and sigils
Numbers
Strings
Interpolation and quoting
Arrays
push, pop, shift and splice
Hashes
keys, values, exists and delete
Scalar and list context
Conditions and comparison
while, for, next and last
foreach and the default variable
Subroutines
Arguments in @_
References
Nested data structures
Regular expressions: match and anchors
Captures and named groups
Substitution with s///
split and join
grep and map
Sort and the Schwartzian transform
Read and write files
File tests and metadata
Directories and paths
die, warn and eval
Modules and Exporter
CPAN and cpanm
Objects with bless
Modern objects with Moo
Testing with Test::More
strict, warnings and diagnostics
Options with Getopt::Long
Environment and %ENV
system, backticks and pipes
One-liners with -n and -p
CSV and TSV processing
JSON with JSON::PP
HTTP clients with HTTP::Tiny
Sockets and IO::Socket
Databases with DBI
Capstone: todo CLI
Capstone: log report
Performance and profiling
Modern Perl tour
Hero roadmap: the whole course on one page
Install Perl on Windows 11
Install Perl on Ubuntu
Install Perl on Rocky Linux
Install Perl on macOS
Install Perl on FreeBSD
Perl in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: