in reply to When does while set $_ ?


This is explained in perlop in relation to <>:
Ordinarily you must assign the returned value to a vari­ able, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a `while' state­ ment (even if disguised as a `for(;;)' loop), the value is automatically assigned to the global variable $_.
--
John.

Replies are listed 'Best First'.
Re: When does while set $_ ?
by crenz (Priest) on Aug 01, 2002 at 09:28 UTC

    Thanks, John. I did read the man pages, but didn't find this one. I guess I just naturally assumed that the while statement should assign $_.

    Is there any (simple) way to assign the outer $_ inside the match() function when in a while-loop? Or would that involve some major hacking?


      You could localise $_ as follows:
      while (local $_ = match('a')) { print "- $_\n"; }

      However, it would be better to use grep() instead of your match() function. Then all of your code could be replaced with the following line: ;-)     print "- $_\n" for grep {/a/} @data;

      --
      John.

        Thanks. Unfortunately, using grep() is not an option -- the original match() could involve multiple m// or a SQL query, depending on the data interface selected ;-).

        But I wonder how four grep()'s compare to four m//'s in a foreach loop... I guess the latter approach still wins, because the array needs to be traversed only once.