I was reading the most recent article on perl.com, and a code segment
reminded me of something I see rather often in code that I don't like.
Here's the code, Perl6ized:
... ;
my $is_ok = 1;
for 0..6 -> $t {
if abs(@new[$t] - @new[$t+1]) > 3 {
$is_ok = 0;
last;
}
}
if $is_ok {
push @moves: [$i, $j];
}
...
I see this idiom a lot in code. You loop through some values on a
condition, and do something only if the condition was never true.
$is_ok is a control flow variable, something I like to minimize. Now,
there are other ways to do this:
if (0..6 ==> grep -> $t { abs(@new[$t] - @new[$t+1]) })
{ ... }
But one would say that's not the cleanest thing in the world.
Python pulled this idiom out in to the syntax (yay them), with C<else>
on loops. The else block on a python loop executes only if you never
broke out of the loop. That's a great idea.
So, in Perl's postmodern tradition, I think we should steal that idea.
I'm a little uneasy about calling it C<else>, though. Maybe C<FINISH>
would do, making the example:
for 0..6 -> $t {
if abs(@new[$t] - @new[$t+1]) > 3 {
last;
}
FINISH {
push @moves: [$i, $j];
}
}
I'd also like to say that while converting the rest of this sub to Perl
6, I realized how much I love the ..^ and ^.. operators. I was
wondering whether people had forgotten about them :-).
Luke