Array Basics
In Perl, you use the @ sigil to work with arrays. An array is a data structure that stores multiple scalar values in order. This page covers declaration, element access, slices, and basic operations.
Syntax
# ========================================
# Declaring and initializing arrays
# ========================================
# Declare with a list
my @names = ("Goku", "Vegeta", "Piccolo");
# Use qw// to create a whitespace-delimited list (no quotes needed)
my @levels = (9000, 8000, 3500);
# Declare an empty array
my @empty = ();
# ========================================
# Accessing elements (index is 0-based)
# ========================================
my $first = $names[0]; # First element: "Goku"
my $second = $names[1]; # Second element: "Vegeta"
my $last = $names[-1]; # Last element (negative index): "Piccolo"
# ========================================
# Getting the array size
# ========================================
my $count = scalar(@names); # Number of elements: 3
my $last_idx = $#names; # Last index: 2
# ========================================
# Adding and removing elements
# ========================================
push @names, "Frieza"; # Append to the end
my $popped = pop @names; # Remove from the end ("Frieza")
unshift @names, "Gohan"; # Prepend to the front
my $shifted = shift @names; # Remove from the front ("Gohan")
# ========================================
# Slices (retrieving multiple elements at once)
# ========================================
my @heroes = ("Goku", "Vegeta", "Piccolo", "Frieza", "Gohan");
my @slice = @heroes[0, 2, 4]; # Get elements at index 0, 2, and 4
my @range = @heroes[1..3]; # Get elements at index 1 through 3
Syntax reference
| Syntax / Function | Description |
|---|---|
| my @array = (val1, val2, ...); | Declares an array and initializes it with values. |
| my @array = qw/val1 val2/; | Uses qw// to write a whitespace-delimited list concisely (no quotes needed). |
| $array[index] | Gets or sets the element at the specified index (0-based). |
| $array[-1] | Gets an element counted from the end using a negative index. |
| scalar(@array) | Returns the number of elements in the array. |
| $#array | Returns the last index of the array (number of elements minus 1). |
| push @array, value; | Appends one or more values to the end of the array. |
| pop @array; | Removes and returns the last element of the array. |
| unshift @array, value; | Prepends one or more values to the front of the array. |
| shift @array; | Removes and returns the first element of the array. |
| @array[0, 2, 4] | Gets a slice by specifying multiple indexes. |
| @array[1..3] | Gets a slice using the range operator ... |
| reverse @array | Returns a list with the array elements in reverse order. |
| sort @array | Returns a sorted list of the array (default is string order). |
Sample code
dragonball_array.pl
#!/usr/bin/perl
# ========================================
# dragonball_array.pl — Manages Dragon Ball character
# information using arrays
# ========================================
use strict;
use warnings;
use feature 'say';
# ----------------------------------------
# Declare character names and power levels as arrays
# ----------------------------------------
my @names = ("Goku", "Vegeta", "Piccolo", "Frieza", "Gohan");
my @powers = (150000000, 120000000, 1000000, 530000, 2000000);
my @races = qw/Saiyan Saiyan Namekian Frieza-race Half-Saiyan/;
# ----------------------------------------
# Check element count and last index
# ----------------------------------------
my $count = scalar(@names);
my $last_idx = $#names;
say "Character count: " . $count;
say "Last index: " . $last_idx;
say "";
# ----------------------------------------
# Access each element by index
# ----------------------------------------
say "=== Character Profiles ===";
for my $i (0 .. $#names) {
# Use printf to align columns
printf "%-16s Race: %-16s Power: %d\n",
$names[$i], $races[$i], $powers[$i];
}
say "";
# ----------------------------------------
# Get the last element using a negative index
# ----------------------------------------
say "First character: " . $names[0];
say "Last character: " . $names[-1];
say "";
# ----------------------------------------
# push / pop to append and remove from the end
# ----------------------------------------
say "=== push / pop ===";
push @names, "Goten";
say "End after push: " . $names[-1]; # Goten
my $popped = pop @names;
say "Removed by pop: " . $popped; # Goten
say "";
# ----------------------------------------
# unshift / shift to prepend and remove from the front
# ----------------------------------------
say "=== unshift / shift ===";
unshift @names, "Krillin";
say "Front after unshift: " . $names[0]; # Krillin
my $shifted = shift @names;
say "Removed by shift: " . $shifted; # Krillin
say "";
# ----------------------------------------
# Use a slice to retrieve multiple elements at once
# ----------------------------------------
say "=== Slices ===";
my @saiyan_pair = @names[0, 1]; # Goku and Vegeta
say "Saiyan pair: " . join(", ", @saiyan_pair);
my @middle = @names[1..3]; # Index 1 through 3
say "Middle 3: " . join(", ", @middle);
say "";
# ----------------------------------------
# Sort power levels in descending order
# ----------------------------------------
say "=== Power Level Ranking (descending) ===";
my @sorted_powers = sort { $b <=> $a } @powers; # <=> is the numeric comparison operator
for my $p (@sorted_powers) {
say $p;
}
say "";
# ----------------------------------------
# Reverse the array
# ----------------------------------------
say "=== Characters in reverse ===";
my @reversed = reverse @names;
say join(", ", @reversed);
perl dragonball_array.pl Character count: 5 Last index: 4 === Character Profiles === Goku Race: Saiyan Power: 150000000 Vegeta Race: Saiyan Power: 120000000 Piccolo Race: Namekian Power: 1000000 Frieza Race: Frieza-race Power: 530000 Gohan Race: Half-Saiyan Power: 2000000 First character: Goku Last character: Gohan === push / pop === End after push: Goten Removed by pop: Goten === unshift / shift === Front after unshift: Krillin Removed by shift: Krillin === Slices === Saiyan pair: Goku, Vegeta Middle 3: Vegeta, Piccolo, Frieza === Power Level Ranking (descending) === 150000000 120000000 2000000 1000000 530000 === Characters in reverse === Gohan, Frieza, Piccolo, Vegeta, Goku
Common mistakes
Using the @ sigil when accessing a single array element
When accessing an individual element of an array, the sigil changes to $. Using @ treats the expression as a slice (an array).
ng_array_sigil.pl
my @names = ("Goku", "Vegeta", "Piccolo");
print @names[0]; # Wrong: treated as a slice and generates a warning
Scalar value @names[0] better written as $names[0] at ng_array_sigil.pl line 2.
Goku
Use the $ sigil to retrieve a single element.
ok_array_sigil.pl
my @names = ("Goku", "Vegeta", "Piccolo");
print $names[0]; # Goku
Goku
Forgetting that sort defaults to string order, not numeric order
The default behavior of sort is lexicographic (string) order. To sort numerically, always provide a { $a <=> $b } block.
ng_sort_numeric.pl
my @powers = (150000000, 9000, 530000);
my @sorted = sort @powers; # Wrong: compared as strings
print join(", ", @sorted) . "\n";
150000000, 530000, 9000
Use the <=> operator to compare values numerically.
ok_sort_numeric.pl
my @powers = (150000000, 9000, 530000);
my @sorted = sort { $a <=> $b } @powers;
print join(", ", @sorted) . "\n";
9000, 530000, 150000000
Summary
Arrays are declared with the @ sigil and hold multiple scalar values in order. When accessing an individual element, the sigil changes to $array[index] — because you are retrieving a single scalar value. Use push / pop to work with the end of an array, and unshift / shift to work with the front. Slices let you extract a sub-array by specifying multiple indexes, such as @array[0, 2]. Because sort defaults to string order, use the <=> (spaceship) operator inside a block to sort numerically.
For basic hash operations, see the Hash (hash_basic) page.
If you find any errors or copyright issues, please contact us.