For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > October 2004 > FAQ: What's a closure?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author FAQ: What's a closure?
PerlFAQ Server

2004-10-19, 4:01 am

This message is one of several periodic postings to comp.lang.perl.misc
intended to make it easier for perl programmers to find answers to
common questions. The core of this message represents an excerpt
from the documentation provided with Perl.

--------------------------------------------------------------------

7.12: What's a closure?


Closures are documented in the perlref manpage.

*Closure* is a computer science term with a precise but hard-to-explain
meaning. Closures are implemented in Perl as anonymous subroutines with
lasting references to lexical variables outside their own scopes. These
lexicals magically refer to the variables that were around when the
subroutine was defined (deep binding).

Closures make sense in any programming language where you can have the
return value of a function be itself a function, as you can in Perl.
Note that some languages provide anonymous functions but are not capable
of providing proper closures: the Python language, for example. For more
information on closures, check out any textbook on functional
programming. Scheme is a language that not only supports but encourages
closures.

Here's a classic function-generating function:

sub add_function_generator {
return sub { shift + shift };
}

$add_sub = add_function_generator();
$sum = $add_sub->(4,5); # $sum is 9 now.

The closure works as a *function template* with some customization slots
left out to be filled later. The anonymous subroutine returned by
add_function_generator() isn't technically a closure because it refers
to no lexicals outside its own scope.

Contrast this with the following make_adder() function, in which the
returned anonymous function contains a reference to a lexical variable
outside the scope of that function itself. Such a reference requires
that Perl return a proper closure, thus locking in for all time the
value that the lexical had when the function was created.

sub make_adder {
my $addpiece = shift;
return sub { shift + $addpiece };
}

$f1 = make_adder(20);
$f2 = make_adder(555);

Now "&$f1($n)" is always 20 plus whatever $n you pass in, whereas
"&$f2($n)" is always 555 plus whatever $n you pass in. The $addpiece in
the closure sticks around.

Closures are often used for less esoteric purposes. For example, when
you want to pass in a bit of code into a function:

my $line;
timeout( 30, sub { $line = <STDIN> } );

If the code to execute had been passed in as a string, "'$line =
<STDIN>'", there would have been no way for the hypothetical timeout()
function to access the lexical variable $line back in its caller's
scope.



--------------------------------------------------------------------

Documents such as this have been called "Answers to Frequently
Asked Questions" or FAQ for short. They represent an important
part of the Usenet tradition. They serve to reduce the volume of
redundant traffic on a news group by providing quality answers to
questions that keep coming up.

If you are some how irritated by seeing these postings you are free
to ignore them or add the sender to your killfile. If you find
errors or other problems with these postings please send corrections
or comments to the posting email address or to the maintainers as
directed in the perlfaq manual page.

Note that the FAQ text posted by this server may have been modified
from that distributed in the stable Perl release. It may have been
edited to reflect the additions, changes and corrections provided
by respondents, reviewers, and critics to previous postings of
these FAQ. Complete text of these FAQ are available on request.
Michele Dondi

2004-10-19, 8:56 pm

On Tue, 19 Oct 2004 04:10:18 +0000 (UTC), PerlFAQ Server
<comdog@panix.com> wrote:

> sub make_adder {
> my $addpiece = shift;
> return sub { shift + $addpiece };
> }
>
> $f1 = make_adder(20);
> $f2 = make_adder(555);


# perl closure.pl
Warning: Use of "shift" without parentheses is ambiguous at
closure.pl line 3.
Type of arg 1 to shift must be array (not private variable) at
closure.pl line 3
, near "$addpiece }"
Execution of closure.pl aborted due to compilation errors.


What about

return sub { $addpiece + shift };

?


PS: I had already posted something about this in 2K2. Got no reply,
AFAIK...


Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{po
p^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
brian d foy

2004-10-19, 8:56 pm

In article <b1jan01c2o4443r4jlalfq4l4htvbbei55@4ax.com>, Michele Dondi
<bik.mido@tiscalinet.it> wrote:

> On Tue, 19 Oct 2004 04:10:18 +0000 (UTC), PerlFAQ Server
> <comdog@panix.com> wrote:


[color=darkred]
> # perl closure.pl
> Warning: Use of "shift" without parentheses is ambiguous at
> closure.pl line 3.


> What about
>
> return sub { $addpiece + shift };


> PS: I had already posted something about this in 2K2. Got no reply,
> AFAIK...


what's 2K2? If you have corrections for the perlfaq, you can
send them to the perlfaq-workers@perl.org. One of us will see
it and be able to fix it. :)

--
brian d foy, comdog@panix.com
Sherm Pendley

2004-10-19, 8:56 pm

brian d foy wrote:

> what's 2K2?


2050. ;-)

sherm--

--
Cocoa programming in Perl: http://camelbones.sourceforge.net
Hire me! My resume: http://www.dot-app.org
Tad McClellan

2004-10-20, 3:56 am

brian d foy <comdog@panix.com> wrote:

> what's 2K2?



Isn't that one of those really tall mountains?


--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
brian d foy

2004-10-20, 3:56 am

In article <slrncnbqmj.3cs.tadmc@magna.augustmail.com>, Tad McClellan
<tadmc@augustmail.com> wrote:

> brian d foy <comdog@panix.com> wrote:
>
[color=darkred]
> Isn't that one of those really tall mountains?


maybe it's two of them.

still though, I'm kinda curious what it really is and if
people are discussing the perlfaq there. I can't pick up
changes if I don't know where people are talking about it. :)

--
brian d foy, comdog@panix.com
Randal L. Schwartz

2004-10-20, 8:56 am

>>>>> "brian" == brian d foy <comdog@panix.com> writes:
[color=darkred]
[color=darkred]

brian> maybe it's two of them.

Uh, 2K2. As in "2002". You guys need to spend more time in chat
rooms. :)

print "Just another Perl hacker,"; # the original

--
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
<merlyn@stonehenge.com> <URL:http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
Bernard El-Hagin

2004-10-20, 8:56 am

NNTP-Posting-Host: airbus.lido-tech.net
X-Trace: nemesis.news.tpi.pl 1098271417 6414 62.89.127.66 (20 Oct 2004 11:23:37 GMT)
X-Complaints-To: usenet@tpi.pl
NNTP-Posting-Date: Wed, 20 Oct 2004 11:23:37 +0000 (UTC)
User-Agent: Xnews/5.04.25
Xref: number1.nntp.dca.giganews.com comp.lang.perl.misc:554079

merlyn@stonehenge.com (Randal L. Schwartz) wrote:

>
>
>
> brian> maybe it's two of them.
>
> Uh, 2K2. As in "2002". You guys need to spend more time in chat
> rooms. :)



Or maybe *you* need to spend *less* time in chat rooms. ;-)


--
Cheers,
Bernard
Alan J. Flavell

2004-10-20, 8:56 am

On Wed, 20 Oct 2004, Randal L. Schwartz wrote:

> Uh, 2K2. As in "2002".


Under normal conventions, "kilo" (one thousand) is written with lower
case "k". 2**10 (1024) is sometimes expressed with upper-case K.

Almost entirely off-topic: the Cambridge Titan (1960's) used to have a
couple of odd units, the "long second" (128 centiseconds) of computing
time, and the "short foot" (10.24 inches) of plotter output.
Michele Dondi

2004-10-20, 4:05 pm

On Tue, 19 Oct 2004 17:47:19 -0500, brian d foy <comdog@panix.com>
wrote:

>
>what's 2K2? If you have corrections for the perlfaq, you can


Ok, just faking to be a youngster! (Hope the term is correct, I'm not
a native English speaker...)

>send them to the perlfaq-workers@perl.org. One of us will see
>it and be able to fix it. :)


Good point pointing it out: actually I already knew, but as they
"used" to say here, repetita iuvant! However since I'm not an expert
myself, I prefer to propose some discussion in this ng to let more
knowledgeable people know. For example I'd suggest

sub { $something + shift };

but someone may think that for beginners

sub { shift() + $something };

would be better...


Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{po
p^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
Tad McClellan

2004-10-20, 4:06 pm

Michele Dondi <bik.mido@tiscalinet.it> wrote:
> On Tue, 19 Oct 2004 17:47:19 -0500, brian d foy <comdog@panix.com>
> wrote:
>
>
> Ok, just faking to be a youngster!



Then just say "dude" a lot.


--
Tad McClellan SGML consulting
tadmc@augustmail.com Perl programming
Fort Worth, Texas
Brian McCauley

2004-10-20, 4:06 pm



Michele Dondi wrote:

> On Tue, 19 Oct 2004 17:47:19 -0500, brian d foy <comdog@panix.com>
> wrote:
>
>
>
>
> Ok, just faking to be a youngster! (Hope the term is correct, I'm not
> a native English speaker...)


Dunno about English, but in Europe and in engineering, 2k2 is short for
2200.

Brian McCauley

2004-10-20, 4:06 pm



Sherm Pendley wrote:

> brian d foy wrote:
>
>
> 2050. ;-)


No, 2200

John W. Kennedy

2004-10-21, 3:56 am

Alan J. Flavell wrote:
> On Wed, 20 Oct 2004, Randal L. Schwartz wrote:
>
>
>
>
> Under normal conventions, "kilo" (one thousand) is written with lower
> case "k". 2**10 (1024) is sometimes expressed with upper-case K.


But is correctly written "Ki".
--
John W. Kennedy
"The pathetic hope that the White House will turn a Caligula into a
Marcus Aurelius is as naïve as the fear that ultimate power inevitably
corrupts."
-- James D. Barber (1930-2004).
Peter J. Acklam

2004-10-21, 3:57 am

Tad McClellan <tadmc@augustmail.com> wrote:

> brian d foy <comdog@panix.com> wrote:
>
>
> Isn't that one of those really tall mountains?


No, that's K2, also known as Mt. Godwin Austen. :-)

Peter

--
#!/local/bin/perl5 -wp -*- mode: cperl; coding: iso-8859-1; -*-
# matlab comment stripper (strips comments from Matlab m-files)
s/^((?:(?:[])}\w.]'+|[^'%])+|'[^'\n]*(?:''[^'\n]*)*')*).*/$1/x;
Michele Dondi

2004-10-21, 3:57 am

On Wed, 20 Oct 2004 19:25:41 +0100, Brian McCauley <nobull@mail.com>
wrote:

>
>Dunno about English, but in Europe and in engineering, 2k2 is short for
>2200.


D'Oh! I really wish I had never tried to (pretend to) be and
write that joke. To be fair I've seen a ("dude"-oriented) commercial
product by a well known brand, that I won't mention, marked 2k4 or 2K4
(funny charachters, anyway, so I'm not sure). That gave me the
-insane- idea...


Michele
--
{$_=pack'B8'x25,unpack'A8'x32,$a^=sub{po
p^pop}->(map substr
(($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^<R<Y]*YB='
..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,$_,
256),7,249);s/[^\w,]/ /g;$ \=/^J/?$/:"\r";print,redo}#JAPH,
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com