Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
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
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 wandering the Monastery: (6)
As of 2014-09-23 00:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (208 votes), past polls