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

Re: Closure Explanation

by almut (Canon)
on Apr 30, 2010 at 06:22 UTC ( #837701=note: print w/ replies, xml ) Need Help??


in reply to Closure Explanation

Just think of it this way: when a function closes over a lexical variable, that instance of the variable (and its associated storage location) won't be freed, as it normally would when the variable goes out of scope — i.e. it continues to remain accessible to the function.

Note that you can (in theory) have more than one closure sharing the same variable instance (kind of their private global variable). Extending the Anonymous Monk's code:

#!/usr/bin/perl sub make_counter_pair { my $start = shift; warn "lexical variable ".\$start." created"; return ( sub { warn "accessing ".\$start; $start++ }, sub { warn "accessing ".\$start; $start++ } ) } my ($c1, $c2) = make_counter_pair(10); my ($c3, $c4) = make_counter_pair(3); print $c1->() . "\n"; print $c2->() . "\n"; print $c1->() . "\n"; print $c2->() . "\n"; print $c3->() . "\n"; print $c4->() . "\n"; print $c3->() . "\n"; print $c4->() . "\n";

would give

lexical variable SCALAR(0x604ff0) created at ./837669.pl line 5. lexical variable SCALAR(0x6323f0) created at ./837669.pl line 5. accessing SCALAR(0x604ff0) at ./837669.pl line 8. 10 accessing SCALAR(0x604ff0) at ./837669.pl line 12. 11 accessing SCALAR(0x604ff0) at ./837669.pl line 8. 12 accessing SCALAR(0x604ff0) at ./837669.pl line 12. 13 accessing SCALAR(0x6323f0) at ./837669.pl line 8. 3 accessing SCALAR(0x6323f0) at ./837669.pl line 12. 4 accessing SCALAR(0x6323f0) at ./837669.pl line 8. 5 accessing SCALAR(0x6323f0) at ./837669.pl line 12. 6

As you can see by looking at the addresses, each pair of closures shares one variable, so the respective value is incremented every time one of the two counter functions is called.


Comment on Re: Closure Explanation
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2014-10-02 01:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (41 votes), past polls