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.

while (my $entry = match('a')) { print "- $entry\n"; # prints the correct results }
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.)
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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.