[oak perl] until loop(s)
Steve Fink
sfink at reactrix.com
Mon Mar 28 12:30:07 PST 2005
Sandy Santra wrote:
> I'm learning (struggling with) "until" loops today. I want an "until"
> control structure that "breaks out" when a condition is fulfilled.
>
> Can anyone find the problem in the below loop? (It never breaks out.)
> Thanks.
>
> use strict;
> print "Can you create world peace in five tries? Type a solution
> below:\n";
> my $number;
> until (my $counter == 5)
>
> {
> while ($number=<STDIN>)
> {
> $counter=$counter+1;
> print "Counter is now $counter.\n";
> print "You still have a few tries left.\n";
> }
> }
> print "You failed! The human race is doomed!\n";
The problem is scoping. The 'my' inside of the counter makes this code
similar to:
until (something) {
my $counter;
$counter = $counter + 1;
}
so every time through the loop, it resets $counter to undef.
There's no equivalent code to insert in place of "something", because I
think it is using the correct $counter variable. It's really closer to
until (0) {
my $counter;
last if $counter == 5;
$counter = $counter + 1;
}
But if you change your code to
my $counter;
until ($counter == 5) {
...$counter = $counter + 1...
}
it will work.
I would have expected your original to work, honestly. But I also never
stick 'my' into the middle of expressions, other than a few limited
cases. Makes my head hurt too much.
More information about the Oakland
mailing list