in reply to understanding closures

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

Replies are listed 'Best First'.
Re^2: understanding closures
by reasonablekeith (Deacon) on Sep 26, 2005 at 08:15 UTC
    The named sub there is a closure, but only in a trivial sense

    Thanks demerphq, I understand this now. I can see that the power of closure comes when you're using them dynamically, hence why all the examples show anonymous sub references. However, using these simple examples has really helped my understanding, so ++ all round.

    Rob

    ---
    my name's not Keith, and I'm not reasonable.