Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

This code is a little unusual. The do {} is a runtime construct to allow you to put statements where an expression is expected. It has scope, but is not actually block (iirc) in that you can't use next to exit out of it.

D:\dev>perl -e"do { next };" Can't "next" outside a loop block at -e line 1. D:\dev>perl -e"{ next };"

The named sub there is a closure, but only in a trivial sense, and you'll probably more likely see people talk about "static" vars in this situation. For instance I would expect to see that code written something like:

BEGIN { my $count=0; # static sub counter {$count++} } for (0..9) { print counter(); }

Without the do on there the block is really a block (albeit a magic one), and its clear the $count=0 is only going to be executed once, and its going to occur before counter() is ever used, that is immediately after the block is compiled (because of the BEGIN).

If you want to make a counter factory then you get into more interesting forms of closures:

sub make_counter { my $start=shift||0; return sub {$start++}; }
---
$world=~s/war/peace/g


In reply to Re: understanding closures by demerphq
in thread understanding closures by reasonablekeith

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (4)
As of 2024-04-26 08:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found