P6 Gentle Intro, Part 2

Part 1 available here.

Arrays

A Perl 6 arrays is an ordered container for a list of scalar items - meaning, you can count on the order of items in the array. Here are some ways to create lists and assign them to an array:

my @primes1 = 2 , 3 , 5 , 7 , 11 , 13; # using the comma operator
my @primes2 = <17 19 23 29 31>;        # same as the comma seperated list
my @primes3 = @primes1 , @primes2;     # this works, giving a single combined list

Functions and operators which return lists also work. For example the range operator:

my @range1 = 1 .. 10;
my @range2 = 'a' .. 'j' ; # it's magic :)

Note that assigning a list to an array will "use up" all available items - the following will not assign anything to @p2:

my (@p1 , @p2) =  <2 3 5 7 11 13> , <17 19 23 29 31>; # @p1 is the same as @primes3, @p2 is an empty array

In order to get a specific value from an array we add square brackets after the array name and use an integer index starting from 0 (for the first element). Here are some examples:

my @primes = <2 3 5 7 11 13>;

my $first  = @primes[0];  # $p1 = 2
my $last   = @primes[@primes.end]; # @primes.end - the last index

Although all of my examples so far have been of arrays containing only numbers, lists and arrays can as I said contain any scalar. For example:

my @mixed = "this list" , 'has' , 4 , "elements";

To print all the elements of the list or array you could do something like "@array.say" or "say @array" (which is the same) but the output would be all of the elements without any spaces between them - not very pretty:

@mixed.say ; # prints "this listhas4elements"

Perl 6 provides us instead with several different options:

@mixed.perl.say ; # prints the data structure as perl6 understands it. In this case: ["this list", "has", 4, "elements"]  -- great for debugging!

say "@mixed[]"; # prints "this list has 4 elements" -- Adding empty square brackets to the array var inside double quotes causes a whitespace seperated list of values to be printed.
say "{@mixed}"; # exactly the same output, but relies on curly braces doing interpolation

Finally here is a random selection of a few array/list methods:

my @r1 = 1 .. 10;

@r1.pop.say; # remove the last element from an array and return it
@r1.perl.say ; # now only 1 .. 9

@r1.push(11); # append one or more elements to an array. In this example, 11
@r1.perl.say ; # now 1 .. 9 , 11

@r1.reverse.perl.say ; # 11 , 9 .. 1

See Synopsys 32 - Containers for more list and array methods.

Leave a comment

About Offer Kaye

user-pic I blog about Perl.