>>>>>> "BRH" == Bryan R Harris <[email protected]> writes:
>
> BRH> Much to my chagrin I realized this morning that this notation:
>
> BRH> while(<FILE>) {
>
> BRH> evaluates as:
>
> BRH> while(defined($_ = <FILE>)) {
>
> BRH> ... and NOT as:
>
> BRH> while(defined(local $_ = <FILE>)) {
>
> BRH> I had a subroutine that was set up to read and parse a file, but it was
> BRH> trashing the value of $_ out in the main program!
>
> BRH> If I use:
>
> BRH> foreach (<FILE>) {
>
> BRH> ... it works perfectly (though slurping the whole file right at the
> start, I
> BRH> know).
>
> how would that work any better as $_ is still set to each element?
Because somehow the $_ is localized with foreach where it is not with the
implicit (?) while loop.
> BRH> My question is: why? Seems like such an easy thing to have done.
>
> it would be better for you to use lexical vars then you wouldn't need to
> worry about action at a distance with $_. also the code reads better as
> you know what you are working with instead of the generic $_. this are two
> of the reasons why i always teach to avoid $_ in most code. use it where
> you must (grep, map, foreach modifier) or where it really helps out the
> code. for line loops, it doesn't help at all so avoid it. and lexicals
> are safer and if well named, better for maintaining the code.
I actually love using $_. It saves all kinds of typing when doing lots of
regex'ing, e.g.:
while(<FILE>) {
s/^\s*#.+//;
s/\^/**/g;
s/(\d)e(\d)/$1E$2/g;
if (!/\S/) { push @lines, $_; }
}
I don't see why it "doesn't help at all" in these kinds of loops.
- Bryan
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/