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"; }
In reply to When does while set $_ ? by crenz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |