Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: What is the scope of $_?

by Athanasius (Monsignor)
on Nov 26, 2012 at 14:55 UTC ( #1005681=note: print w/ replies, xml ) Need Help??


in reply to What is the scope of $_?

$_ is global in scope (see perlvar#General-Variables). However, in

sub xyz() { foreach(4..5) { ...

$_ is implicitly localised, as though written:

sub xyz() { foreach local $_ (4..5) { ...

which explains the behaviour you’re seeing.

Update: From perlsyn#Foreach-Loops:

If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop.

Hope that helps,

Athanasius <°(((><contra mundum


Comment on Re: What is the scope of $_?
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (8)
As of 2014-12-26 09:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (169 votes), past polls