Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: closures: anonymous subs vs function templates?

by Anonymous Monk
on Dec 21, 2014 at 09:53 UTC ( [id://1110943]=note: print w/replies, xml ) Need Help??


in reply to closures: anonymous subs vs function templates?

What is a 'function template?' local *name = sub {}; versus my $name = sub {}; are both created using anonymous subs. The assignment operator makes them go to different places though (sym table and lexpad, resp.). Then the difference between them is the same as the difference between all other local/my variables...
use 5.020; use warnings; outer1(); exit 0; sub outer1 { my $hello = 'hello'; local *inner = sub { say $hello; }; outer2(); } sub outer2 { inner(); } __END__ hello

Replies are listed 'Best First'.
Re^2: closures: anonymous subs vs function templates?
by 5haun (Scribe) on Dec 21, 2014 at 13:02 UTC

    Thank you for that example. When edited as shown below, it clearly highlighted the differences:

    use warnings; use v5.14; outer1(); exit 0; sub outer1 { my $hello = 'hello'; # local *inner = sub { my $inner = sub { say $hello; }; outer2(); } sub outer2 { # inner(); $inner->(); } __END__ Global symbol "$inner" requires explicit package name at /tmp/subtst.p +l line 20. Execution of /tmp/subtst.pl aborted due to compilation errors.

    Compared with your example, we can show the more limited scope of the lexical form, as recommended by Laurent_R. Thank you both!

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-25 14:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found