Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re^3: "$_" vs. $_

by blazar (Canon)
on Apr 08, 2007 at 11:09 UTC ( #608888=note: print w/replies, xml ) Need Help??

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.)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://608888]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2020-08-13 17:53 GMT
Find Nodes?
    Voting Booth?
    Which rocket would you take to Mars?

    Results (74 votes). Check out past polls.