Lists, Arrays and Ranges

9.1 Lists vs Arrays

A List is immutable (its elements can't be reassigned). An Array is a List of mutable Scalar containers.

my $list = (1, 2, 3);          # List
my @array = 1, 2, 3;           # Array (assignment to @ creates an Array)
@array[0] = 10;                # OK
# $list[0] = 10;               # error: Cannot modify an immutable Int
say @array, ' ', $list.WHAT, ' ', @array.WHAT;   # [10 2 3] (List) (Array)

9.2 Array Operations

my @a = <apple banana cherry>;
say @a[0], ' ', @a[*-1], ' ', @a[1..2], ' ', @a[0, 2];   # indexing; *-1 = last
say @a.elems, ' ', @a.end, ' ', +@a;                     # 3 2 3
@a.push('date');       @a.append(<elder fig>);           # push one item / append a list's elements
@a.unshift('apricot'); @a.prepend(<x y>);
my $last = @a.pop;     my $first = @a.shift;
@a.splice(1, 2);                                         # remove 2 at index 1
@a.splice(1, 0, 'kiwi', 'lime');                         # insert
say @a.reverse, ' ', @a.sort, ' ', @a.sort(*.chars), ' ', @a.sort({ $^b cmp $^a });
say @a.join(', '), ' ', @a.first(*.starts-with('k')), ' ', @a.grep(/an/);
say @a.map(*.uc), ' ', @a.unique, ' ', @a.pick, ' ', @a.rotate(1);
say @a.head(2), ' ', @a.tail(2), ' ', @a.skip(1);
say (1, 2, 3).sum, ' ', <3 1 2>.max, ' ', (1, 2, 2, 3).repeated;
say [1, [2, [3, 4]]].flat, ' ', (1, (2, 3)).flat;        # flattening rules: Arrays itemize sub-arrays
say ((1, 2), (3, 4)).map(*.sum);                          # (3 7)
say @a.kv, ' ', @a.pairs, ' ', @a.keys, ' ', @a.antipairs;
say @a.classify(*.chars);                                 # hash of length => items
say (1..10).batch(3), ' ', (1..6).rotor(
…

9.3 Ranges

say 1..5;                 # 1..5
say (1..5).list;          # (1 2 3 4 5)
say ^5;                   # 0..^5
say (^5).list;            # (0 1 2 3 4)
say 1..^5, ' ', 1^..5;    # excluding endpoints
say ('a'..'e').list;      # (a b c d e)
say (1..10).grep(*.is-prime);
say 5 ~~ 1..10, ' ', 3.5 ~~ 1..5;   # True True (ranges match numerically)
say (1, 3 ... 11);        # sequence with a step (see Module 12)
say (10...1);             # countdown
say (1..Inf)[^5];         # infinite range, take the first 5
say (1..10).pick(3);
say (1..10).minmax, ' ', (1..10).bounds;