Skip to content

Perl Arrays

An array in Perl is an ordered list of scalar values. Array variable names are prefixed with an “at” sign (@). To access a single element of an array, you use a dollar sign ($) with the array name, followed by the element’s index in square brackets (e.g., $array[0]).

It’s standard practice to use use strict; and use warnings; at the beginning of your Perl scripts for better error checking and code quality.

Example of array declaration and access:

#!/usr/bin/perl
use strict;
use warnings;
my @ages = (25, 30, 40);
my @names = ("John Paul", "Lisa", "Kumar");
print "Ages[0]: $ages[0]\n"; # Output: Ages[0]: 25
print "Ages[1]: $ages[1]\n"; # Output: Ages[1]: 30
print "Names[1]: $names[1]\n"; # Output: Names[1]: Lisa
# Print all elements of an array
print "All names: @names\n"; # Output: All names: John Paul Lisa Kumar

In Perl, “list” refers to the ordered collection of data itself, while “array” is a variable that holds such a list.

Arrays are typically created using parentheses () or the qw// (quote word) operator for lists of simple strings.

my @numbers = (1, 2, 3, 4, 5);
my @strings = ('apple', 'banana', 'cherry');
# Using qw// for lists of words (automatically quotes them and splits by whitespace)
my @weekdays = qw(Mon Tue Wed Thu Fri Sat Sun);
# Equivalent to: my @weekdays = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
# qw can use other delimiters too:
my @colors = qw!red green blue!;
my @symbols = qw#alpha beta gamma#;

You can also create an empty array: my @empty_array = ();

Array indices start at 0. You can also use negative indices to access elements from the end of the array (-1 is the last element, -2 is the second to last, etc.).

#!/usr/bin/perl
use strict;
use warnings;
my @days = qw(Mon Tue Wed Thu Fri Sat Sun);
print "First day: $days[0]\n"; # Output: First day: Mon
print "Third day: $days[2]\n"; # Output: Third day: Wed
print "Last day: $days[-1]\n"; # Output: Last day: Sun
print "Second to last: $days[-2]\n"; # Output: Second to last: Sat

Perl’s range operator .. can be used to create arrays of sequential numbers or letters.

#!/usr/bin/perl
use strict;
use warnings;
my @first_ten = (1..10); # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
my @some_letters = ('a'..'f'); # ('a', 'b', 'c', 'd', 'e', 'f')
print "Numbers: @first_ten\n";
print "Letters: @some_letters\n";

To get the number of elements in an array, evaluate the array in scalar context.

my @my_array = (10, 20, 30);
my $size = @my_array; # $size is 3
print "Array size: ", scalar(@my_array), "\n"; # Another way to force scalar context
print "Array size: $#my_array + 1\n"; # $#array gives the last index

$#array_name gives the index of the last element in @array_name. So, the size is $#array_name + 1. If the array is empty, $#array_name is -1.

Perl provides functions to add/remove elements from the beginning or end of an array:

FunctionDescription
push @ARRAY, LISTAppends elements of LIST to the end of @ARRAY. Returns the new number of elements.
pop @ARRAYRemoves and returns the last element of @ARRAY.
unshift @ARRAY, LISTPrepends elements of LIST to the beginning of @ARRAY. Returns the new number of elements.
shift @ARRAYRemoves and returns the first element of @ARRAY.
#!/usr/bin/perl
use strict;
use warnings;
my @fruits = qw(apple banana);
print "Initial: @fruits\n";
push @fruits, 'orange', 'grape';
print "After push: @fruits\n"; # apple banana orange grape
my $last_fruit = pop @fruits;
print "Popped: $last_fruit, Array: @fruits\n"; # grape, Array: apple banana orange
unshift @fruits, 'mango';
print "After unshift: @fruits\n"; # mango apple banana orange
my $first_fruit = shift @fruits;
print "Shifted: $first_fruit, Array: @fruits\n"; # mango, Array: apple banana orange

An array slice allows you to select multiple elements from an array by their indices, forming a new list (which can be assigned to another array).

#!/usr/bin/perl
use strict;
use warnings;
my @days = qw(Mon Tue Wed Thu Fri Sat Sun);
# Get specific elements
my @work_days = @days[0, 1, 2, 3, 4]; # Mon Tue Wed Thu Fri
print "Work days: @work_days\n";
# Get a range of elements
my @mid_week = @days[1..3]; # Tue Wed Thu (indices 1, 2, 3)
print "Mid week: @mid_week\n";
# Slices can use any valid indices, including negative ones
my @ends = @days[0, -1]; # Mon Sun
print "Ends: @ends\n";

The splice function is powerful for modifying arrays: it can remove elements, add new elements, or do both at a specific position.

splice @ARRAY, OFFSET, [LENGTH, [LIST]]
  • @ARRAY: The array to modify.
  • OFFSET: Starting index for modification. Negative offset counts from the end.
  • LENGTH (optional): Number of elements to remove starting from OFFSET.
  • LIST (optional): Elements to insert into the array at OFFSET after removing LENGTH elements.

splice returns a list of the elements removed from @ARRAY.

#!/usr/bin/perl
use strict;
use warnings;
my @letters = ('a'..'g'); # a b c d e f g
print "Original: @letters\n";
# Remove 2 elements starting at index 2 ('c', 'd')
my @removed = splice @letters, 2, 2;
print "Removed: @removed, Array: @letters\n"; # Removed: c d, Array: a b e f g
# Reset for next example
@letters = ('a'..'g');
# Remove 1 element at index 1 ('b') and insert 'X', 'Y'
@removed = splice @letters, 1, 1, 'X', 'Y';
print "Removed: @removed, Array: @letters\n"; # Removed: b, Array: a X Y c d e f g
# Reset for next example
@letters = ('a'..'g');
# Insert 'Z' at index 3 without removing anything
splice @letters, 3, 0, 'Z';
print "Array after insert: @letters\n"; # a b c Z d e f g

The split function breaks a string into a list of substrings based on a delimiter pattern.

split /PATTERN/, EXPR, [LIMIT]
#!/usr/bin/perl
use strict;
use warnings;
my $csv_data = "apple,banana,cherry,date";
my @fruits = split /,/, $csv_data;
print "Fruits: @fruits\n"; # Fruits: apple banana cherry date
my $sentence = "This is a sample sentence.";
# Split by whitespace (default if PATTERN omitted or is ' ')
my @words = split /\s+/, $sentence; # Using explicit whitespace pattern
# my @words = split ' ', $sentence; # Common idiom for splitting on whitespace
print "Words: @words\n"; # Words: This is a sample sentence.
# Limit the number of splits
my $path = "/usr/local/bin/perl";
my @parts = split /\//, $path, 3; # Limit to 3 parts (2 splits)
print "Path parts: @parts\n"; # Path parts: usr local/bin/perl (first part is empty due to leading /)

The join function combines the elements of a list into a single string, using a specified separator string.

join SEPARATOR, LIST
#!/usr/bin/perl
use strict;
use warnings;
my @items = qw(one two three four);
my $joined_string = join '-', @items;
print "Joined with '-': $joined_string\n"; # Joined with '-': one-two-three-four
my $no_sep_string = join '', @items;
print "Joined with empty: $no_sep_string\n"; # Joined with empty: onetwothreefour

The sort function sorts a list and returns the sorted list. By default, it sorts alphabetically (ASCIIbetical order).

sort [SUBROUTINE_OR_BLOCK] LIST
#!/usr/bin/perl
use strict;
use warnings;
my @names = qw(Alice Charlie Bob David);
my @sorted_names = sort @names;
print "Sorted names (alpha): @sorted_names\n"; # Alice Bob Charlie David
my @numbers = (10, 2, 100, 5, 25);
my @alpha_sorted_numbers = sort @numbers;
print "Sorted numbers (alpha): @alpha_sorted_numbers\n"; # 10 100 2 25 5 (wrong for numeric)
# Numeric sort using a comparison block
my @numerically_sorted_numbers = sort { $a <=> $b } @numbers;
print "Sorted numbers (numeric): @numerically_sorted_numbers\n"; # 2 5 10 25 100
# Reverse numeric sort
my @reverse_numeric = sort { $b <=> $a } @numbers;
print "Sorted numbers (reverse numeric): @reverse_numeric\n"; # 100 25 10 5 2

Inside the sort block, $a and $b are special package variables holding two elements being compared. The block should return -1 if $a comes before $b, 0 if they are equal, or 1 if $a comes after $b. The spaceship operator <=> does this for numbers, and cmp does it for strings.

The $[ Special Variable (Deprecated and Removed)

Section titled “The $[ Special Variable (Deprecated and Removed)”

Older versions of Perl had a special variable $[ that could change the starting index of arrays (default 0). This variable is heavily deprecated and its use has always been strongly discouraged. It was removed entirely in Perl 5.30 (released in 2019). Do not use $[ in modern Perl code. All arrays in Perl are 0-indexed.

You can merge arrays by simply including them in a list assigned to a new array.

#!/usr/bin/perl
use strict;
use warnings;
my @odd = (1, 3, 5);
my @even = (2, 4, 6);
my @numbers = (@odd, @even, 7, 8);
print "Merged numbers: @numbers\n"; # 1 3 5 2 4 6 7 8
# You can also embed list literals directly
my @mixed = (10, 20, (30, 40), 50);
print "Mixed: @mixed\n"; # 10 20 30 40 50

You can apply array indexing and slicing directly to a list literal (a list in parentheses).

#!/usr/bin/perl
use strict;
use warnings;
my $third_element = (10, 20, 30, 40, 50)[2];
print "Third element from list: $third_element\n"; # 30
my @slice_from_list = (qw(a b c d e f))[1..3];
print "Slice from list: @slice_from_list\n"; # b c d