Mostly Harmless Docs/Arrays

my @a = 1, 2, 3;           # no parens required

@a = 'foo', 'bar', 'baz';  # or
@a = <foo bar baz>;        # (same as above)

@a[0];        #=> 'foo'
@a[*-1]       #=> 'baz'  (last one)

my @b = <a b c>;
my @c = @a, @b;   #=> 1 2 3 a b c  (array concatenation)

@b.keys       #=> 0, 1, 2   (indices as keys)

@a = <h i j k l m n o p>;
@a[3..7]      #=> k l m n o   (array slice)
@a[2, 3, 6]   #=> j k n       (also array slice)

@a = <n m l p o>;
"XX {@a} XX"  #=> XX n m l p o XX  (interpolates)

@a.elems      #=> 5   (num of elements)
@a.end        #=> 4   (index of last element)
@a.sort       #=> l m n o p

@a.join('-')  #=> n-m-l-p-o

@a = 1, 2, 3, 4;
@a.reduce({$^a + $^b});  #=> 10

# Many methods won't modify the array, but instead return a modified copy.
@a = <a a b b c c>
@a.uniq             #=> a b c   (@a is not modified)
@a = @a.uniq        # set value of @a to: a b c
@a .= uniq          # same as above
@a.reverse          #=> c b a   (again, @a is not modified)
@a.roll             #=> 1 random element of @a (same as @a.pick)
@a.pick(2)          #=> 2 random elements of @a (not the same)
@a.roll(2)          #=> 2 random elements of @a (possibly the same)
@a.rotate           #=> b c a

# But these will modify it.
@a.push('x')        # @a is now:  a b c x
@a.unshift('z')     # @a is now:  z a b c x

# @a.pop and @a.shift work as you'd expect.

# To delete an item (or items) from an array, use splice, because it's nice.
my @a = <a b c d e>;
@a.splice(1, 3)       #=> b c d   (and modifies @a in-place)
@a                    #=> a e

Some notes:

  • @a .= some-method is short for @a = @a.some-method.

  • re. the difference between pick and roll: when you ask pick for more than one item, it chooses one, then removes it from the poll of possible next-choices. When you ask roll for more than one, it just “rolls the dice” each time, possibly getting the same one it just got.

  • To iterate over an array, see Control Structures.


Main | Next: Pairs