Michael Limberger
Need me? Email mike@limberger.ca
Perl
Goto loops
A label inside else, then jump
This note looks at goto-style loops in Perl. They are unfashionable, and sometimes they are still the clearest way to say what you mean.
#!/usr/bin/env perl
use feature qw|say|;
my $n = 7;
if ($n == 10)
{
say qq|I see a ${n}!|;
}
else
{ R:
say qq(Hmmm... looking for 10... \$n = ${\$n++});
sleep 1;
$n > 10 ? say qq(Yay! It's a ${\--$n}!) : goto R;
}
It counts from 7 toward 10, then celebrates. The overshoot
to 11 is on purpose: the exit test is $n > 10,
then a pre-decrement prints 10.
The landing pad
R: is a label. Labels do not create
scope. Perl will jump to one it can see, even inside
else.
Three flavours
goto LABEL | Classic jump. What this piece uses. |
|---|---|
goto &NAME | Replace the current sub. A real tail call. |
goto EXPR | Computed destination. Do not. |
Never use goto is too strong. Tail calls and generated
state machines have a case. Building a loop inside
else is showing off. Save it for golf.