Arrays
An array is an ordered list of scalars that you reach by position.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Using @fruits[0] when you mean the scalar element $fruits[0]
- Confusing $#array (last index) with the number of elements
- 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: