Perl by Example: Arrays
Managing ordered lists of scalars with this code example showing array declaration with @ sigil, element access using $ sigil for single values, stack and queue operations with push/pop/shift/unshift, and array slicing with range operator.
Code
#!/usr/bin/perl
use strict;
use warnings;
# Arrays start with @
my @animals = ("Camel", "Llama", "Alpaca");
# Accessing elements using $ (since a single element is a scalar)
print "First animal: $animals[0]\n";
# Array operations
push(@animals, "Vicuna"); # Add to end
my $last = pop(@animals); # Remove from end
unshift(@animals, "Guanaco"); # Add to beginning
my $first = shift(@animals); # Remove from beginning
# Array slice
my @subset = @animals[0..1];
# Getting array size
my $size = scalar @animals;
print "Size: $size\n";Explanation
Arrays in Perl are ordered lists of scalar values, denoted by the at sign @ sigil. Arrays are dynamic, automatically growing or shrinking as elements are added or removed. When accessing a single array element, the sigil changes to $ because the result is a scalar value, using square bracket notation like $array[index]. Array indices are zero-based with the first element at position 0.
Perl provides built-in functions for array manipulation treating arrays as stacks or queues. The push() function appends elements to the end, pop() removes and returns the last element, unshift() prepends elements to the beginning, and shift() removes and returns the first element. These functions modify the array in place and automatically adjust its size, making them efficient for dynamic data structures.
Array slices extract multiple elements using the @ sigil because the result is a list. The range operator .. creates sequences like @array[0..2] for the first three elements. The scalar keyword forces array evaluation in scalar context, returning the array length. In list context, arrays return all their elements, while in scalar context they return their size, demonstrating Perl's context-sensitive behavior.
Code Breakdown
my @animals = (...) declares array with @ sigil indicating plurality.$animals[0] accesses single element using $ sigil for scalar result.push/pop for end, unshift/shift for beginning.@animals[0..1] array slice uses @ sigil, range operator extracts elements.
