SPUG: interesting while() behavior and hosting recs
John W. Krahn
krahnj at telus.net
Thu Sep 30 23:25:34 CDT 2004
Joel Grow wrote:
> Hey Perl gurus, I recently noticed this very strange (to me at least)
> while() behavior:
>
> my $count = 1;
> while() { # this evaluates to true(!)
> print "hello world\n";
> last if (++$count > 3);
> }
>
> Prints "hello world" 3 times. How is () evaluated to true?!?
>
> If I put "0", "undef", "", or a scalar set to any of those in the parens,
> it does what I expect--it skips the while loop. I thought "Hmm, maybe
> this is a strange empty list issue?", but no, the code below still skips
> the while loop:
>
> my $count = 1;
>
> my @empty = ();
>
> while(@empty) { # skips this while loop, as I'd expect
> print "hello world\n";
> last if (++$count > 3);
> }
>
> In desperation, I thought maybe while() was evaluating $_ by default,
> since you can of course do:
>
> while (<STDIN>) {
>
> but printing out $_ just before the while() loop showed it is undefined.
>
> What's going on?
That is working for the same reason that
for ( ;; ) { ... }
works in Perl as well as in C where Perl inherited it from.
John
--
use Perl;
program
fulfillment
More information about the spug-list
mailing list