in reply to Reii: Should we Localize $_ ?
in thread Should we Localize $_ ?

I don't get what you're saying. If you have a construct like while (<>) or foreach(@arr) you get a newly scoped $_:
sub doit { my @array = qw(1 2 3 4); # this doesn't damage outer @array: $_ = 'xyz' foreach (@array); } my @array = qw(a b c d); print join("|", @array), "\n"; foreach (@array) { my $f = doit('abcd'); } print join("|", @array), "\n";

Replies are listed 'Best First'.
Re: Re: Reii: Should we Localize $_ ?
by dragonchild (Archbishop) on Jun 13, 2001 at 23:52 UTC
    Try the following with and without the 'local $_;' line and you'll see what he's talking about.

    use strict; sub getfile { local $_; my $filename = shift; local *F; open F, "< $filename" or die "Couldn't open `$filename': $!"; my $contents; while (<F>) { s/#.*//; # Remove comments next unless /\S/; # Skip blank lines $contents .= $_; # Save current (nonblank) line } return $contents; } my @array = ("base_tester", "Foo.pm"); foreach (@array) { my $filename = $_; my $f = getfile($filename); } print "@array\n";
    That's what I tried to see the effects, and I was rather surprised.
Reiv: Should we Localize $_ ?
by John M. Dlugosz (Monsignor) on Jun 13, 2001 at 23:56 UTC
    No, while(<>) does not create a newly scoped $_.

    Behold:

    require 5.6.1; use strict; use warnings; my @array= (1,2,3,4,5); foo() foreach (@array); print "@array\n"; sub foo { while (<DATA>) { return } # silly, but makes a small example with little input. } __DATA__ clobbered clobbered clobbered clobbered clobbered