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

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 } } }

2019-03-07 Athanasius fixed closing code tag

Replies are listed 'Best First'.
Re: $_ confusion with loops in loops
by NetWallah (Canon) on Mar 06, 2019 at 19:56 UTC
    Please review your <code> tag - the formatting in your node is messed up.

    It is likely that when your sub "search" returns a value that is not ==1, it sets $_.

    my $rtn = search ($fields[0], UNUSED);

                    As a computer, I find your faith in technology amusing.

      You can fix this problem by declaring $_ with 'local' in the search routine.
      sub search { local $_; ... }

      The previous value of $_ is restored when search returns ($_ goes out of scope).

      Bill

        You could do that, or you could use a lexical variable with a sensible name that not only completely avoids the issue, but also makes the code easier to read.

        Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond