Arrays in Perl

In Perl, an array is an ordered list of scalars. Arrays are commonly used in Perl for various purposes.

#!/usr/bin/perl
use strict;
use warnings;

# Here we create an array @a that will hold 5 elements.
# By default, an array is empty, so we need to initialize it.
my @a = (0, 0, 0, 0, 0);
print "emp: @a\n";

# We can set a value at an index using the $array[index] = value syntax,
# and get a value with $array[index].
$a[4] = 100;
print "set: @a\n";
print "get: $a[4]\n";

# The scalar context of an array returns its length.
print "len: ", scalar @a, "\n";

# Use this syntax to declare and initialize an array in one line.
my @b = (1, 2, 3, 4, 5);
print "dcl: @b\n";

# You can use the qw() operator to create an array of strings without quotes and commas.
@b = qw(1 2 3 4 5);
print "dcl: @b\n";

# Perl doesn't have a direct equivalent to Go's [...] syntax with index specification.
# However, we can achieve a similar result using the $#array syntax to set the last index.
@b = (100);
$#b = 4;  # This makes the array have 5 elements
$b[3] = 400;
$b[4] = 500;
print "idx: @b\n";

# Array types are one-dimensional, but you can
# use references to build multi-dimensional data structures.
my @twoD;
for my $i (0..1) {
    for my $j (0..2) {
        $twoD[$i][$j] = $i + $j;
    }
}
print "2d: @{$twoD[0]} @{$twoD[1]}\n";

# You can create and initialize multi-dimensional arrays at once too.
@twoD = (
    [1, 2, 3],
    [1, 2, 3],
);
print "2d: @{$twoD[0]} @{$twoD[1]}\n";

Note that arrays in Perl are displayed with spaces between elements when printed with the @array syntax.

To run the program, save it as arrays.pl and use perl:

$ perl arrays.pl
emp: 0 0 0 0 0
set: 0 0 0 0 100
get: 100
len: 5
dcl: 1 2 3 4 5
dcl: 1 2 3 4 5
idx: 100 0 0 400 500
2d: 0 1 2 1 2 3
2d: 1 2 3 1 2 3

Perl arrays are dynamic and can grow or shrink as needed. They don’t have a fixed size like in some other languages. The $#array syntax allows you to manipulate the last index of an array, which can be used to resize it.