crenz has asked for the wisdom of the Perl Monks concerning the following question:
I hope this is not too dumb a question :-) While working on a dictionary module, I came up with the following question: Why is $_ not set in a while loop like the following one? I would expect it to work like while (<>) { # do stuff }
while (match('a')) { print "- $_\n"; # $_ is undef all the time }
I can fix it using a loop variable, but it doesn't look as sexy and it doesn't help me to understand why the first option doesn't work.
Here's an example match function to let you understand what it's all about. When having searched all entries, the function returns undef. (Note that in the original problem match returns a reference, but the problem is the same.)while (my $entry = match('a')) { print "- $entry\n"; # prints the correct results }
my $matchPos = 0; sub match { my ($key) = @_; while ($matchPos < @data) { $matchPos++; return $data[$matchPos - 1] if ($data[$matchPos - 1] =~ /$key/); } return undef; } while (match('a')) { print "- $_\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: When does while set $_ ?
by jmcnamara (Monsignor) on Aug 01, 2002 at 08:09 UTC | |
by crenz (Priest) on Aug 01, 2002 at 09:28 UTC | |
by jmcnamara (Monsignor) on Aug 01, 2002 at 10:02 UTC | |
by crenz (Priest) on Aug 01, 2002 at 10:34 UTC | |
|
Re: When does while set $_ ?
by Anonymous Monk on Aug 01, 2002 at 08:06 UTC |