LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 818 min read

Arrays

Learn Perl arrays: the @ sigil, indexing elements, push/pop/shift/unshift, and how an array behaves in scalar context.

Introduction

Arrays let you store an ordered collection of values in a single variable, rather than creating a separate scalar for every item. If scalars are Perl's way of holding one thing, arrays are Perl's way of holding many things in a specific order — perfect for lists of usernames, file paths, log lines, or numbers.

What You Will Learn
  • What an array is and how the @ sigil works.
  • How to declare, fill, and access array elements by index.
  • How to add and remove elements with push, pop, shift, and unshift.
  • Why an array in scalar context gives you its length.

What is an Array?

An array is an ordered, numbered list of scalar values. Array variable names always use the @ sigil, which signals "this variable holds multiple values" — the plural counterpart to the singular $ sigil used for scalars.

use strict;
use warnings;
my @fruits = ("apple", "banana", "cherry");
print "Fruits: @fruits\n";
Program Output

Click Run to see what this code prints.

Just like scalars, arrays are interpolated inside double-quoted strings — Perl automatically joins the elements with a single space between them by default.

Declaring and Accessing Arrays

Arrays are declared with my, just like scalars, followed by a parenthesized, comma-separated list of initial values.

use strict;
use warnings;
my @days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
my @empty = (); # an array can also start empty
print "Number of weekdays listed: ", scalar(@days), "\n";
Program Output

Click Run to see what this code prints.

scalar(@days) forces the array into scalar context, which returns its element count — we will look at this pattern more closely later in this lesson.

Indexing Elements

To access a single element of an array, switch the sigil to $ (because you are now asking for one scalar value) and provide the numeric index in square brackets. Perl array indexes start at 0, and negative indexes count backward from the end of the array.

use strict;
use warnings;
my @days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
print "First day: $days[0]\n";
print "Third day: $days[2]\n";
print "Last day: $days[-1]\n";
print "Second-to-last day: $days[-2]\n";
Program Output

Click Run to see what this code prints.

Sigil Switch Rule

This trips up nearly every Perl beginner: use @ when referring to the whole array (@days), but switch to $ when accessing a single element ($days[0]), because a single element is a scalar.

Adding and Removing: push, pop, shift, unshift

Perl provides four core built-in functions for growing and shrinking an array from either end.

FunctionEffect
push(@array, $value)Adds one or more values to the end of the array.
pop(@array)Removes and returns the last value from the array.
shift(@array)Removes and returns the first value from the array.
unshift(@array, $value)Adds one or more values to the beginning of the array.
use strict;
use warnings;
my @queue = ("task1", "task2");
push(@queue, "task3"); # add to the end
unshift(@queue, "urgent-task"); # add to the beginning
print "Queue: @queue\n";
my $next_up = shift(@queue); # remove from the beginning
print "Processing: $next_up\n";
print "Remaining queue: @queue\n";
my $last_task = pop(@queue); # remove from the end
print "Removed from end: $last_task\n";
print "Final queue: @queue\n";
Program Output

Click Run to see what this code prints.

Array Length in Scalar Context

Perl arrays behave differently depending on whether they are used in list context or scalar context. When an array is evaluated in scalar context — for example, assigned to a scalar variable, or explicitly wrapped in scalar(...) — it evaluates to its element count, not its contents.

use strict;
use warnings;
my @colors = ("red", "green", "blue", "yellow");
my $count = @colors; # scalar context: assigns the length, 4
my $last_index = $#colors; # $#array gives the index of the last element
print "Number of colors: $count\n";
print "Last valid index: $last_index\n";
Program Output

Click Run to see what this code prints.

$#colors is a special notation that gives the index of the final element (always one less than the total count, since indexing starts at 0). This scalar-vs-list distinction is such a core Perl concept that an entire upcoming lesson, "Variables & Context," is dedicated to it.

Looping Over an Array

The foreach loop is the most natural way to process every element of an array in turn.

use strict;
use warnings;
my @scores = (88, 92, 79, 95);
foreach my $score (@scores) {
print "Score: $score\n";
}
Program Output

Click Run to see what this code prints.

Common Mistakes

Avoid These Mistakes
  • Using @ instead of $ when accessing a single element, e.g. writing @days[0] (a slice) instead of $days[0].
  • Assuming array indexes start at 1 — they start at 0.
  • Forgetting that pop and shift modify the original array in place, rather than returning a copy while leaving it unchanged.
  • Confusing @array (the array itself) with scalar(@array) (its element count) when printing or comparing.

Best Practices

  • Use foreach to process every element rather than manually looping with numeric indexes when you do not need the index itself.
  • Reach for push/pop when treating an array like a stack, and shift/unshift when treating it like a queue.
  • Use scalar(@array) explicitly when you specifically want the count, for clarity.
  • Give arrays plural names (@users, @scores) to make code more self-documenting.

Frequently Asked Questions

Perl returns undef (an undefined value) rather than throwing an error, though use warnings; may flag the use of an uninitialized value if you then try to use that result.

Yes. A Perl array can hold scalars of any kind in any combination, since each element is simply a scalar value.

$days[0] accesses a single scalar element. @days[0] is technically a one-element array slice, which behaves similarly for a single index but is a different, less common construct — always prefer $days[0] for single elements.

Key Takeaways

  • Arrays store ordered lists of scalar values and use the @ sigil.
  • Access single elements with the $ sigil and square-bracket indexing, starting at 0.
  • push and unshift add elements; pop and shift remove and return elements.
  • An array in scalar context evaluates to its element count.
  • foreach is the idiomatic way to loop over every element of an array.

Summary

Arrays give you ordered collections of data. Next, you will learn about hashes, which store data as key-value pairs rather than by numeric position, using the % sigil.

Next Lesson →

Hashes