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

Re^2: closure clarity, please

by ikegami (Patriarch)
on Nov 24, 2009 at 18:12 UTC ( [id://809160]=note: print w/replies, xml ) Need Help??


in reply to Re: closure clarity, please
in thread closure clarity, please

Conclusion: always define global subroutines

You have no choice. Named subroutines are always global. You're lying to yourself when you said "local f".

What is a strange behavior is that variables got stuck with a value,

Why do you think that creating a variable somewhere should replace a variable in some unrelated sub?

Replies are listed 'Best First'.
Re^3: closure clarity, please
by vitoco (Hermit) on Nov 24, 2009 at 20:16 UTC
    You have no choice. Named subroutines are always global. You're lying to yourself when you said "local f".

    You are right. I meant "define all subroutines at the same global level."

    Why do you think that creating a variable somewhere should replace a variable in some unrelated sub?

    It is not clear to me when a lexical variable is used and when is lost during the program execution, as in my last example, where I'd expect an uninitialized $a in all "local f"'s messages.

      Ok, I can understand that confusion. Lexicals are actually allocated very early on (compile-time?) and on scope exit. This allows for the creation of private variables:
      package Foo; my $x; sub set_x { validate($_[0]); $x = $_[0]; } sub get_x { die("uninitialized") if !defined($x); $x } 1;
      or
      { my $x; sub set_x { validate($_[0]); $x = $_[0]; } sub get_x { die("uninitialized") if !defined($x); $x } }
        Lexicals are actually allocated very early on (compile-time?)
        I think that it must be true that lexicals are allocated at compile time—at least, if my timeline in Re^4: closure clarity, please is anything near the correct one. I can't see any other reason why the call to f on line 27 of Re^3: closure clarity, please (which I called step 9) would be affected by the call to g on line 23 (which I called step 7). (In fact, I thought that I stole this observation from a post of yours that I read long ago ….)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-20 01:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found