Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^3: Scope, package, and 'my' variables

by friedo (Prior)
on Jan 04, 2005 at 19:56 UTC ( [id://419386]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Scope, package, and 'my' variables
in thread Scope, package, and 'my' variables

This is due to closures. With the braces, your first sub, do_a is defined within the lexical scope that sets $var to 'first var'. In other words:

{ my $var = 'first var'; # sets $var for this block # defines a sub IN this block, so gets this $var sub do_a { print "In 'aaa' var is set to '$var'\n"; } }

Because subroutine names are available globally, do_a can be called from anywhere, but gets the $var defined in its lexical block.

Similarly, do_b is defined in a block where $var is set to nothing, and do_c is in a block with no $var at all.

Replies are listed 'Best First'.
Re^4: Scope, package, and 'my' variables
by ff (Hermit) on Jan 04, 2005 at 20:14 UTC
    In my original question, yes, that makes sense. But in my clarifying question, in which there are braces around the code in package bbb, why doesn't that set up an independent version of $var which then should get picked up by do_b and thus print out "second time for var"?

    Thanks

    package bbb; { use strict; use warnings 'all'; my $var = 'second time for var'; sub do_b { print "In 'bbb' var is set to '$var'\n"; } }

      It does declare a new lexical $var over which do_b closes. However, you call the subroutine before the assignment occurs.

      The issue is that the assignment of $var within the block under bbb never happens before you call do_b. Don't think of a line like my $x = somevalue; as a declaration of a variable to be initialized before the program begins. Think of it as a statement that runs when the program gets to it.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (6)
As of 2024-04-25 15:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found