This has been a hot topic at my workplace and my boss came up with this example for showing how closures work.
#!/usr/local/bin/perl use strict; my $dave = new Foo ("dave", "oranges", "grapefruit"); $dave->("debug message"); package Foo; sub new { my ($class, @stuff) = @_; return sub { doit(@stuff, @_) }; # <-- closure here? } sub doit { print shift, ": ", join(",", @_), "\n"; }
Prepare to correct me if I'm wrong - I think what we've got here is a constructor (sort of) that returns a reference to an anonymous subroutine. When we call new() we're also setting $class and @stuff in the namespace of that anonymous subroutine to be "dave" and ("oranges", "grapefruit") respectively.

When I run this thing I get:

dave: oranges,grapefruit,debug message

Ok, so this is kind of neat, now I understand how you can use one constructor and some properties in order to respond with a reference to an anonymous subroutine of your choosing, but what I'm curious about is - is this -really- a closure?

I'm not completely versed in how long values like $class and @stuff would live inside a sub - only for the duration of the execution of the sub, right?

The closure (or rather using those values in the anonymous sub) makes these values live on past the execution of the sub, right?

Super Confused, -mr.dunstan

In reply to Why are closures cool, continued? by mr.dunstan

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.