Course of Raku / Essentials / More about types / Positional data types
Arrays
Arrays are aggregate data types that can keep more than one value. That distinguishes arrays from scalar items. Array 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.
my @cities;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';Indexing
To access a single item of an array, use a pair of brackets that you place after the name of the variable:
say @cities[1];Notice that the sigil always stays the same. As elements are counted
from zero, the element @cities[1] is 'Rome' in
our example.
Arrays are mutable, so you can easily modify its items by simply assigning a new value to them:
@cities[0] = 'Rome';
@cities[1] = 'Paris';After this, the statement say @cities[1] will print the
new value 'Paris'.
Size
To get the current length of an array, or, in other words, the number
of its elements, use the elems method:
say @cities.elems; # 3If the array appears in a context, where the expected parameter is a number, the return value is the size of the array:
say +@cities; # 3Here, the +
prefix operator requires a numeric value from its argument, so the
result of +@cities is 3.
Practice
Complete the quiz that covers the contents of this topic.
Course navigation
← Positional data types | Quiz — Arrays →
💪 Or jump directly to the exercises in this
section.
Translations of this page: English • Deutsch • Español • Italiano • Latviešu • Nederlands • Български • Русский • Українська