Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^2: What is the scope of $_?

by Lotus1 (Chaplain)
on Nov 26, 2012 at 19:46 UTC ( #1005754=note: print w/ replies, xml ) Need Help??


in reply to Re: What is the scope of $_?
in thread What is the scope of $_?

If all the OP's examples use the global $_ then printing it at the end would show the last value assigned. What actually happens is a warning for 'Use of uninitialized value $_ ...' The subroutine uses whatever $_ that is in scope when it is called.

use warnings; use strict; sub abc() { $_ = 'x'; } foreach(1..2) { my $loopvar = 'in the loop'; print "Before:$_\n"; abc(); print "After:$_\n"; } print "\$_ = $_\n"; # warning for uninitialized value $_ (global scop +e) abc(); print "\$_ = $_\n"; # prints $_ = x


Comment on Re^2: What is the scope of $_?
Select or Download Code
Replies are listed 'Best First'.
Re^3: What is the scope of $_?
by tobyink (Abbot) on Nov 26, 2012 at 23:16 UTC

    As I said, all the OP's examples use the global $_ but some Perl control structures localize that variable.

    The same effect is illustrated here using global $::x...

    use warnings; use strict; sub abc() { $::x = 'x'; } foreach $::x (1..2) { print "Before:$::x\n"; abc(); print "After:$::x\n"; } print "\$::x = $::x\n"; # warning for uninitialized value $x (global +scope) abc(); print "\$::x = $::x\n"; # prints $x = x
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      So when the foreach loop finishes it restores the undef value to $_. Thanks.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (16)
As of 2015-07-30 16:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (273 votes), past polls