In this screencast I provide a basic introduction to arrays in Perl 6.
Instead of using the REPL, in what you would now type EVAL instead of eval, here I am showing you the examples running from the command line.
Create an array, print the values:
examples/arrays/01.p6
use v6; my @names = ("Foo", "Bar", "Moo"); say @names;
$ perl6 01.p6 Foo Bar Moo
Print the values in a way more useful for debugging:
examples/arrays/01_perl.p6
use v6; my @names = ("Foo", "Bar", "Moo"); say @names.perl;
$ perl6 01_perl.p6 Array.new("Foo", "Bar", "Moo")
Element of an array:
examples/arrays/01_element.p6
use v6; my @names = ("Foo", "Bar", "Moo"); say @names[1];
$ perl6 01_element.p6 Bar
Perl 5 users should note, the sigil has not changed! In Perl 6 there is sigil-invariance.
examples/arrays/01_all_elements.p6
use v6; my @names = "Foo", "Bar", "Moo"; say @names[];
$ perl6 01_all_elements.p6 Foo Bar Moo
No need for parentheses around the elements of a list in assignment:
examples/arrays/01_no_parens.p6
use v6; my @names = "Foo", "Bar", "Moo"; say @names[];
$ perl6 01_no_parens.p6 Foo Bar Moo
Normally arrays don't interpolate in a string:
examples/arrays/02_interpolate.p6
use v6; my @names = "Foo", "Bar", "Moo"; say "Hello @names how are you?";
$ perl6 02_interpolate.p6 Hello @names how are you?
However, if we put quare brackets after the arrat then we can achive interpolation:
examples/arrays/02_interpolate_with_square.p6
use v6; my @names = "Foo", "Bar", "Moo"; say "Hello @names[] how are you?";
$ perl6 02_interpolate_with_square.p6 Hello Foo Bar Moo how are you?
We can interpolate a single element of the array:
examples/arrays/02_interpolate_element.p6
use v6; my @names = "Foo", "Bar", "Moo"; say "Hello @names[1] how are you?";
$ perl6 02_interpolate_element.p6 Hello Bar how are you?
A more generic way would be to put the expression in curly braces:
examples/arrays/02_interpolate_with_curly.p6
use v6; my @names = "Foo", "Bar", "Moo"; say "Hello {@names} how are you?";
$ perl6 02_interpolate_with_curly.p6 Hello Foo Bar Moo how are you?
Inside the curly braces we can put any expression. Perl 6 will evaluate the expression and the result will be interpolated in the string.
examples/arrays/03.p6
use v6; my @names = "Foo", "Bar", "Moo"; say "Hello { join('; ', @names) } how are you?";
$ perl6 03.p6 Hello Foo; Bar; Moo how are you?
Using pointy brackets to create an array is like qw in Perl 5. examples/arrays/04.p6
use v6; my @names = <Foo Bar Moo>; say "Hello {@names} how are you?";
$ perl6 04.p6 Hello Foo Bar Moo how are you?
Iterating over the elements of an array using the for loop:
examples/arrays/05.p6
use v6; my @names = <Foo Bar Moo>; for @names -> $n { say $n; }
$ perl6 05.p6 Foo Bar Moo
Published on 2015-02-02