Camelia
Prev: Looping over any number of elements

Missing values

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?
examples/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).

examples/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

examples/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:

examples/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

Prev: Looping over any number of elements

Table of Contents

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus

Perl 6 Tricks and Treats newsletter

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