http://qs321.pair.com?node_id=608888


in reply to Re^2: "$_" vs. $_
in thread "$_" vs. $_

Now that you pointed out what is, in retrospect, the obvious, it's easier to see when you do an identical thing:
my $bar = "world"; sub foo { while (@_) { $bar = shift; $params->{$bar} = shift; }

It's not, strictly speaking, the same thing: the big difference being that $_ is a package variable and your $bar above, a lexical one.

It is perhaps interesting in this respect to notice that a lexical $_ is provided in blead; to quote from there:

Lexical $_

The default variable $_ can now be lexicalized, by declaring it like any other lexical variable, with a simple

my $_;

The operations that default on $_ will use the lexically-scoped version of $_ when it exists, instead of the global $_.

In a map or a grep block, if $_ was previously my'ed, then the $_ inside the block is lexical as well (and scoped to the block).

In a scope where $_ has been lexicalized, you can still have access to the global version of $_ by using $::_, or, more simply, by overriding the lexical declaration with our $_.


Back to stable, you've been repeatedly pointed to local, in which case it's also worth pointing out that experienced Perl hackers often told me that

local $_=whatever;

can break because of a bug with Perl tied variables that may bite you in the neck first or later:

#!/usr/bin/perl -l use strict; use warnings; use Tie::Array; my @q = my @q0 = qw/foo bar/; sub foo { local $_ = 'baz'; print "@q $_"; } foo for @q; tie @q, 'Tie::StdArray'; @q=@q0; print '-' x 11; foo for @q; __END__

(Learnt in clpmisc and probably adapted from an example posted there by someone else.)