Camelia

Operation on a Series of Integers in Perl 6

Iterating over a series of integers in a range is similar in Perl 6 to the same code in Perl 5 except of slightly different format of the foreach loop that is spelled only as for now.

Note! This site is about Perl 6.
If you are looking for a solution for the current production version of Perl 5, please check out the Perl 5 tutorial.

my $x = 23;
my $z = 27;

for $x .. $z -> $i {
    say $i;
}

Will print the numbers 23, 24, 25, 26, 27 as expected.

C-style loop

C-style, 3-part for loops are also available in Perl 6 and they are called loop but they are not really recommended. Better to use the for loop as described above. You could say this, but it has the same issues with off-by-one errors as we have already learned to avoid in Perl 5.

my $x = 23;
my $z = 27;
loop (my $i = $x; $i <= $z; $i++) {
    say $i;
}

Series

Iterating over every 2nd number is also possible with the for loop of Perl 6 but this time, instead of 2 dots, we are using 3. Instead of a Range we are talking about a Series here.

We set the first two element of te series and the upper limit.

my $x = 23;
my $z = 27;
for $x, $x+2 ... $z  -> $i {
	say $i;
}

This will print 23, 25, 27

You could play with it more. Just one thing to remember, you have to have the upper to be exact:

for 1, 3 ... 7  -> $i {
	say $i;
}

This will work and print 1, 3, 5, 7

OTOH this

for 1, 3 ... 8  -> $i {
	say $i;
}

will freak out Rakudo which will be stuck in a loop trying to reach infinity.

And beyond.


The Perl 6 Tricks and Treats newsletter has been around for a while. If you are interested to get special notification when there is new content on this site, it is the best way to keep track:
Email:
Full name:
This is a newsletter temporarily running on my personal site (szabgab.com) using Mailman, till I implement an alternative system in Perl 6.
Gabor Szabo
Written by Gabor Szabo

Published on 2012-07-07



Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus
Suggest a change
Elapsed time: 2.82448731

Perl 6 Tricks and Treats newsletter

Register to the free newsletter now, and get updates and news.
Email:
Name: