Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^4: Closure confusion in Tkx (declarations in loops - inner vs outer)

by LanX (Saint)
on Jul 13, 2019 at 21:35 UTC ( [id://11102804]=note: print w/replies, xml ) Need Help??


in reply to Re^3: Closure confusion in Tkx (declarations in loops - inner vs outer)
in thread Closure confusion in Tkx

> as to why the c-style for fails in this case.

Think of lexicals in a scope like having a different references each time the scope is passed at runtime.

But - like already demonstrated - the first part of the c-style for is outside the block to be implemented as a while.

More gory details?

A lexical declaration in a scope reserves - at run time - a storage place in memory which is released at the end of scope.

No release happens if the ref counter isn't 0, like when the lexical is used in a closure.

So if the last lexical was released it might happen that the ref is reused, but it's better to assume they aren't the same variable.

DB<8> for my $x (1..3) { print \$x } SCALAR(0x3450e50)SCALAR(0x3450e50)SCALAR(0x3450e50) DB<9> for my $x (1..2) { print \$x; $a = sub {$x} } SCALAR(0x3459b20)SCALAR(0x3328238)

$x has different refs in line 9 because the first $x is captured in a closure and not relased.

Hence Perl can't reuse the reference.

HTH! :)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

  • Comment on Re^4: Closure confusion in Tkx (declarations in loops - inner vs outer)
  • Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2024-04-19 23:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found