Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: closures: anonymous subs vs function templates?

by Laurent_R (Canon)
on Dec 21, 2014 at 10:49 UTC ( [id://1110945]=note: print w/replies, xml ) Need Help??


in reply to closures: anonymous subs vs function templates?

Both syntaxes use anonymous subs (but they are not really closures in your examples). The first syntax is writing the sub identifier into the symbol table, so that the sub can be called as a normal subroutine (without the -> dereferencing operator), while the second one is using a lexical variable which may have a limited scope and lifespan.

Personally, I would tend to use only the lexical form (with scope) unless I had a good specific reason to do otherwise.

Replies are listed 'Best First'.
Re^2: closures: anonymous subs vs function templates?
by 5haun (Scribe) on Dec 21, 2014 at 13:06 UTC
    Thank you for the description. When combined with the example from Anonymous Monk, it was helpful in demonstrating the extent of scope of each of the two forms. The lexical form is certainly more limited.
      The lexical form is certainly more limited.
      I don't really agree with that sentence. Being able to limit the scope is usually extremely useful. It not only reduces the risk of errors associated with global variables (and other global identifiers), but it also makes it possible to build very powerful constructs.

      Perl 5.0 introduced lexical variables, Perl 5.6 introduced lexical file and directory handles, Perl 5.18 introduced lexical subroutines, the tendency over the years has been to go more and more for lexical "things". Because they add a lot of expressive power to the language.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2024-04-19 00:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found