in reply to detecting changes in a localised variable

As TedYoung points out, while (<>) doesn't localize $_ and this is likely where it is getting clobberd.

<plug>Here's a short talk on the subject.</plug> Here are some interesting comments I got about it last time it was mentioned. (Especially Aristotle's surprising remark that no Perl construct implicitly localizes $_ at all!)

Replies are listed 'Best First'.
Re^2: detecting changes in a localised variable
by BrowserUk (Patriarch) on Feb 19, 2005 at 16:08 UTC
    Especially Aristotle's surprising remark that no Perl construct implicitly localizes $_ at all!)

    Hmm. I understand Aristotle's point, but I think his assertion is wrong.

    P:\test>perl -le"$_='old value';@a=1..10; for(@a){ $_++ }; print;" old value

    Here, for is aliasing $_ to each of the values in @a, but it localises $_ first! Hence, after the loop, $_ regains it's former value.

    Perl could implicitly localise $_ for the duration of a while loop in the same way giving this:

    P:\test>type junk.dat|perl -e"$_='old value';{local$_; while(<>){print +};}print;" line 1 line 2 line 3; old value

    instead of this:

    P:\test>type junk.dat|perl -e"$_='old value';while(<>){ print};print;" line 1 line 2 line 3;

    As for why it doesn't, that's a question for those with the historical perspective.


    Examine what is said, not who speaks.
    Silence betokens consent.
    Love the truth but pardon error.
Re^2: detecting changes in a localised variable
by Tanktalus (Canon) on Feb 19, 2005 at 16:10 UTC

    That's a very interesting thread - thank you. I kinda got most of this, although not so clearly. The problem is that not all my co-workers get this, so I sometimes spend time dealing with the ramifications of their code :-) And this was somewhat of the problem here. (The problem was that the writer of the code in question didn't know the ramifications ... and that was me, because it was the first piece of perl code I had ever, ever written - 3+ years old, and in bad need of replacing. My co-workers still don't know the ramifications, however we now have coding standards that bypass the ramifications: while(<FH>) isn't allowed, and $_ should be avoided where it can. map, grep, etc., cannot avoid it, so go ahead there.)

      It's always impossible to know things before you learn them :)

      In the case of $_, the rule of thumb is to treat it as a global that will pollute calling code except where you specifically know it won't, e.g. foreach, map, and grep.

      In 5.9.1, you can lexicalize $_.