Arrays are aggregate data types that can keep more than one value. That differs arrays from scalar items. Array’s elements can be indexed (or subscripted). In other words, its elements have a position (which explains the general name for this kind of data: positionals).
Array variables use another kind of sigil:
@. The rules for the variable name are the same as for scalars.
So far, the array named
@cities has been created. You can fill it with some values:
@cities = 'Paris', 'Rome', 'Berlin';
Alternatively, it is possible to initialise the values immediately:
my @cities = 'Paris', 'Rome', 'Berlin';
To access a single item of an array, use a pair of brackets that you place after the name of the variable:
Notice that the sigil always stays the same. As elements are counted from zero, the element
'Rome' in our example.
Arrays are mutable, so you can easily modify the items of it by simply assigning a new value to them:
@cities = 'Rome'; @cities = 'Paris';
After this, the statement
say @cities will print the new value
To get the current length of an array, or, in other words, the number of its elements, use the
say @cities.elems; # 3
If the array appears in a context, where the expected parameter is a number, the return value is the size of the array:
say +@cities; # 3
+ prefix operator requires a numeric value from its argument, so the result of
Complete the quiz that covers the contents of this topic.
💪 Or jump directly to the exercises to this section.