Introduction to Arrays

When you need to store an ordered list of multiple values, you use an **Array**. Arrays are designated by the "at" sigil (@) (think @ for Arrays/All).

Declaring Arrays

You define an array by grouping scalar elements inside parentheses:

use strict;
use warnings;

my @servers = ("web01", "db01", "cache01");
my @ports   = (80, 443, 3306, 6379);

Accessing Individual Elements

This is a major source of confusion for beginners: because an individual element inside an array is a singular scalar value, you access it using the scalar sigil ($), followed by the variable name and the index number in square brackets (zero-indexed):

# To access the first element ("web01"):
print $servers[0]; 

# To access the second element ("db01"):
print $servers[1];

Checking Array Size

To find out how many items live inside an array, you can evaluate the array in a scalar context (which we will cover deep in Phase 2):

my $count = @servers;
print "We have $count servers active.\n"; # Outputs: We have 3 servers active.
Next Module ->