← Back to Perl Course | Chapter 2: Variables | Lesson 3 of 7

Arrays

An array is an ordered list of scalars that you reach by position.

In this page:

  1. Arrays

Arrays

Array names start with @ and you declare them with my. Elements are accessed with a $ and square brackets, so $fruits[0] is the first element, and negative indexes count from the end. The special expression $#fruits is the last index, and using the array in scalar context gives its length.

Note: Use qw(a b c) to write a list of simple words without quotes or commas.

Example: Arrays

perl
use strict;
use warnings;

my @fruits = qw(apple banana cherry);
print "first: $fruits[0]\n";
print "last: $fruits[-1]\n";
print "last index: $#fruits\n";
print "length: ", scalar(@fruits), "\n";
$fruits[3] = "date";
print "all: @fruits\n";
for my $f (@fruits) {
    print "- $f\n";
}

# Output:
# first: apple
# last: cherry
# last index: 2
# length: 3
# all: apple banana cherry date
# - apple
# - banana
# - cherry
# - date
Common Mistakes
  1. Using @fruits[0] when you mean the scalar element $fruits[0]
  2. Confusing $#array (last index) with the number of elements
  3. Expecting the first element to be at index 1
Chapter Summary
  • Arrays start with @
  • Elements use $array[index]
  • Indexes start at 0 and -1 is the last element
  • $#array is the last index and scalar(@array) the length
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.