Camelia
Prev: Looping over any number of elements

Missing values

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.

One should ask the question what happens if the list runs out of values in the middle, of a multi-value iteration? That is, what happens to the follow loop?

tutorial/arrays/missing_values.p6

#!/usr/bin/env perl6
use v6;

for (1, 2, 3, 4, 5) -> $x, $y {
    say "$x $y";
}
say 'done';

In this case Rakudo throws an exception when it finds out it does not have enough values for the last iteration. It will look like this, (with a bunch of trace information afterwards).

tutorial/arrays/missing_values.p6.output

1 2
3 4
Not enough positional parameters passed; got 1 but expected 2
  in block <anon> at examples/arrays/missing_values.p6:4

In order to avoid the exception we could tell the loop that the second and subsequent values are optional by adding a question mark after the variable

tutorial/arrays/missing_values_fixed.p6

#!/usr/bin/env perl6
use v6;

for (1, 2, 3, 4, 5) -> $x, $y? {
    say "$x $y";
}
say 'done';

This will work but generate the following output:

tutorial/arrays/missing_values_fixed.p6.output

1 2
3 4
use of uninitialized value of type Mu in string context
   in block <anon> at examples/arrays/missing_values_fixed.p6:5
5
done


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-01-01


Prev: Looping over any number of elements

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.9618991

Perl 6 Tricks and Treats newsletter

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