Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
If I'm not mistaken, neither of your examples are closures. According to Intermediate Perl, a closure is "just a subroutine that references a lexical variable that has gone out of scope".

In your first example, while there is an anonymous subroutine reference passed to the find() function, it doesn't reference any lexical variables. In your second example, 1) there is no subroutine, and 2) the $a enclosed in braces is a different variable than the one outside of them.

Note also that your first example was incorrect. It should have been:

use File::Find; my $total_size = 0; find(sub {$total_size += -s if -f}, '.'); print $total_size, "\n";
You were missing the "use" statement, missing a "(" in the find function, and the "{" in the sub definition was misplaced.

An example of a closure from Intermediate Perl) is as follows:
use File::Find; my $callback; { my $count = 0; $callback = sub { print ++$count, ":$File::Find::name\n" }; } find($callback, '.');
So, here the subroutine is a closure because it refers to the lexical variable $count.

Hope this helps.

memnoch

Gloria in Excelsis Deo!

In reply to Re: Closures clarification by memnoch
in thread Closures clarification by props

Title:
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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others surveying the Monastery: (7)
    As of 2021-04-16 10:18 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found

      Notices?