Arrays
| Declaring a list | |
| Index and sigil change | |
| Slices | |
| The last index | |
| Ranges and qw |
Declaring a list
An array holds an ordered list of scalars under a name with the at sign. The parentheses on the right are a list, not a grouping, so commas separate its elements.
my @langs = ("perl", "ruby", "python");
my @sizes = (10, 20, 30);
print "@langs\n"; # perl ruby python
perl demo.pl
perl ruby python
The same name may hold an array and a scalar at once, because the sigil is part of the name. @langs and $langs are separate storage.
Index and sigil change
To read one element you use the dollar sigil, because a single element is a scalar. The brackets carry the index, counting from zero.
my @langs = ("perl", "ruby", "python");
print $langs[0], "\n"; # perl
print $langs[2], "\n"; # python
print $langs[-1], "\n"; # python, last element
perl demo.pl
perl
python
python
Negative indexes count back from the end, so the last element is always -1. That works for arrays and for slices, and it removes most of the off-by-one arithmetic from list code.
Slices
A slice takes several elements at once and keeps their order. The sigil becomes an at sign because the result is a list, and the brackets hold the indexes.
my @langs = ("perl", "ruby", "python");
my @first_two = @langs[0, 1];
print "@first_two\n"; # perl ruby
my @last_two = @langs[-2, -1];
print "@last_two\n"; # ruby python
perl demo.pl
perl ruby
ruby python
The last index
The special form $#array gives the index of the last element, which is one less than the number of elements. Use scalar @array when you want the count itself.
my @langs = ("perl", "ruby", "python");
print $#langs, "\n"; # 2
print scalar @langs, "\n"; # 3
perl demo.pl
2
3
Assigning to $#array truncates or extends the array, so it is a quick way to keep the first ten elements: $#list = 9;
Ranges and qw
The range operator builds a list from two endpoints. Combined with qw, which splits a string on whitespace, it covers most literal lists in real code.
my @digits = (1 .. 5);
my @letters = ("a" .. "e");
my @flags = qw(-v --quiet --dry-run);
print "@digits\n"; # 1 2 3 4 5
print "@letters\n"; # a b c d e
perl demo.pl
1 2 3 4 5
a b c d e
Ranges are lazy about nothing: 1 .. 1_000_000 really builds a million elements. For big sequences use a counting loop from lesson 15 instead.
Next: push, pop, shift and splice
Article author: Arthur Isaev