in reply to Memory efficiency, anonymous vs named's vs local subroutines
Further to GrandFather's reply: Not only is it difficult to figure out how such code works, even then it probably doesn't work the way you (thanos1983) think it does.
Consider the "Variable "$x" will not stay shared at ..." warning(s) you get when you run such code (you are running your code with warnings enabled, right?):
Variable "%s" will not stay shared(See perldiag.) Anonymous subroutines allow proper closures to be formed and maintained.
(W closure) An inner (nested) *named* subroutine is referencing a
lexical variable defined in an outer named subroutine.
When the inner subroutine is called, it will see the value of the
outer subroutine's variable as it was before and during the *first*
call to the outer subroutine; in this case, after the first call to
the outer subroutine is complete, the inner and outer subroutines
will no longer share a common value for the variable. In other
words, the variable will no longer be shared.
This problem can usually be solved by making the inner subroutine
anonymous, using the "sub {}" syntax. When inner anonymous subs that
reference variables in outer subroutines are created, they are
automatically rebound to the current values of such variables.
WRT local-ized subroutine names (or anything else, for that matter), remember that a localized thingy is visible within the scope of all subroutines subsequently invoked within the localizing scope. I.e., its localization is dynamic. A lexical variable (e.g., one holding a code reference) is visible only within the scope of the block in which it is defined, i.e., its scope is, well, lexical. To me, lexical scope is much to be prefered over dynamic scope unless you have a very clear (and well documented) reason for choosing the latter.
As to the difference in memory usage between local-ized and lexical subroutines: I must admit I've done no research or experimentation, but I doubt there is any significant difference.
Give a man a fish: <%-(-(-(-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Memory efficiency, anonymous vs named's vs local subroutines
by thanos1983 (Parson) on Jul 18, 2015 at 19:05 UTC | |
by AnomalousMonk (Archbishop) on Jul 18, 2015 at 21:14 UTC | |
by Laurent_R (Canon) on Jul 19, 2015 at 10:05 UTC |