stanley82 has asked for the wisdom of the Perl Monks concerning the following question:

oops I've maybe got the post right this time I'm a bit messed up with $_ The code below failed to work til I was specific as what to write. In the IF block "print NEW;" worked but in the ELSE block it failed, but once I explicitly used $fields[0] it was fine. $_ has me a bit frustrated with loops in loops as to which $_ I'm using. Regards Ian.

while (<UNMATCHED>) { @fields = split(/:/, $_); $wd = substr($fields[0], 0, 1); if($wd eq "/") { my $rtn = search ($fields[0], UNUSED); #Returns 1 i +f #fields[0] is found in UNUSED. print "Return is = $rtn \n"; if($rtn == 1) { print "Writing to CHANGED. \n"; print CHANGED "$fields[0] \n"; # print NEW; #This works in IF but n +ot in ELSE ? } else { print "Writing to NEW \n"; print NEW "$fields[0] \n"; #This works # print NEW; #This does not } } }

Replies are listed 'Best First'.
Re: $_ confusion with loops in loops
by AnomalousMonk (Archbishop) on Mar 06, 2019 at 20:30 UTC
    while (<UNMATCHED>) { ... }

    It's a little difficult for me to understand just what you expect from the posted code and what "failed to work," but one thing I suspect is that you may be expecting the value of  $_ set in the while-loop quoted above (a block read from a file) to be unchanged throughout the while-loop.

    But while-loops do not "topicalize" the value of  $_ as for-loops do. I also see that there is a
        my $rtn = search ($fields[0], UNUSED);
    statement in the quoted while-loop that seems to be searching a file with the handle UNUSED. If this search uses another
        while (<UNUSED>) { ... }
    while-loop structure, the value of  $_ will be changed and will not be restored upon return to the scope of the posted code unless  $_ was properly local-ized within the search() function.

    I think my advice would be to use lexical variables as the loop variable and in other cases within the block:

    while (my $record = <UNMATCHED>) { my @fields = split(/:/, $record); ... }
    See my. Save your worries about  $_ for for-loops, map and grep built-ins, etc.


    Give a man a fish:  <%-{-{-{-<

Re: $_ confusion with loops in loops
by AnomalousMonk (Archbishop) on Mar 06, 2019 at 20:00 UTC

    Rather than starting a new thread, the better approach would have been to have edited the previous post to simply fix the  <code> ... </code> tags as needed. Please see How do I change/delete my post? for site etiquette and protocol regarding such changes.


    Give a man a fish:  <%-{-{-{-<

Re: $_ confusion with loops in loops
by stanley82 (Novice) on Mar 06, 2019 at 21:37 UTC

    Many thank for the reply. my I understand and the rest makes good sense. I'll do what you demonstrated and not rely on the $_ as much, it's a bit terse anyways. Ian.