in reply to Should we Localize $_ ?

The issue here is not specifically with the magical $_ var, but with aliasing. Perl has a number of cases where variables are aliased, but it's not always clear when this occurs. I consider this to be a feature, and not a bug, but some would disagree. Here are some examples:

# poorly implementing VBScript's 'trim' function: trim( $somevar ); sub somevar { $_[0] =~ s/^\s*//; $_[0] =~ s/\s*$//; }

Ignoring, for the moment, that this is poor code (it probably should return the new value rather than altering the argument - don't get me started on chomp and chop :), this works because the values in @_ are aliases to the original values passed to them.

Another example:

my @array = qw/ 1 2 3 4 5 /; my @new_array = sort { $a++ <=> $b-- } @array;

It looks innocent enough, but @array is now set to: qw/ 0 2 3 4 6 /. Oops! That's probably not what we intended.

You also have the same behavior with $_ in map and grep operators. Even though $_ is involved here, it's a case of needing to be aware of when Perl is aliasing variables, as opposed to copying them

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.