Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Recursive subroutines and closures

by GrandFather (Saint)
on Sep 21, 2022 at 01:50 UTC ( [id://11147044]=note: print w/replies, xml ) Need Help??


in reply to Recursive subroutines and closures

Consider:

use strict; use warnings; Outer(1); Inner(2); sub Outer { my ($param) = @_; sub Inner { my ($innerVar) = @_; print "In inner: $innerVar\n"; } Inner($param); }

Prints:

In inner: 1 In inner: 2

So maybe Inner isn't as encapsulated as you might hope? Now consider:

use strict; use warnings; Outer(1); Inner(); Outer(1); sub Outer { my ($param) = @_; sub Inner { print "In inner: $param\n"; ++$param; } Inner(); }

Prints:

Variable "$param" will not stay shared at 11147042.pl line 12. In inner: 1 In inner: 2 In inner: 3

In this case Inner has closed over $param from the enclosing Outer scope with results that may not be quite what you expected! Note that the second call to Outer doesn't recreate the closure and that the copy of $param used by Inner is that used on the first call to Outer. There are times when this is exactly what you want to happen, but not very often. Placing Inner after Outer makes the code clearer to my eye and without actually closing over variables as in the second example, there doesn't seem to be much advantage in nesting Inner in Outer.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^2: Recursive subroutines and closures
by ibm1620 (Hermit) on Sep 22, 2022 at 02:36 UTC
    Yes, when I added a second argument to make_backup and attempted to read it within _preserve_previous, I got the mysterious Variable will not stay shared warning, which led me to realize I was accidentally creating a closure.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2024-03-28 15:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found