Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re^2: Lexical closures

by spurperl (Priest)
on Oct 25, 2008 at 19:44 UTC ( #719539=note: print w/ replies, xml ) Need Help??


in reply to Re: Lexical closures
in thread Lexical closures

So let me see if I get this correctly... Perl's foreach creates a new lexical scope (i.e. a new binding a.k.a. stack frame) at each iteration.

Python's for loop doesn't do that, and hence the difference in behavior.

Does Perl's for (my $i = 0; $i < $N; ++$i) behave the same way?

I wonder about the tradeoffs here. It seems likely that foreach's creation of new scopes cost something. Does it make it inherenty slower than a for loop that would not create a scope ?


Comment on Re^2: Lexical closures
Download Code
Re^3: Lexical closures
by GrandFather (Cardinal) on Oct 25, 2008 at 20:51 UTC

    No. The confusion is that Perl effectively closes over the value of the variable, not a reference to the variable.

    All languages that I know where you can declare a variable locally to the scope of a block (including a block for a loop) effectively set up a new stack frame on each entry to the block, but the loop variable is outside that block or it couldn't maintain its contents from one iteration to the next.


    Perl reduces RSI - it saves typing
      The confusion is that Perl effectively closes over the value of the variable, not a reference to the variable.
      sub make_funcs { my $val = shift; (sub {$val * $val}, sub {$val++}) } my($f3, $i3) = make_funcs(3); my($f5, $i5) = make_funcs(5); say $f3->(); say $f5->(); $i3->(); say $f3->(); say $f5->(); __END__ 9 25 16 25
      I can't explain my results in combination with your claim.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (2)
As of 2014-09-20 03:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

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











    Results (152 votes), past polls