It dawned on me that in perl you can create a closure without even nesting functions (though you can also do it the "traditional" way). Perl allows you to have unnamed blocks that define their own variable scope, which can take the place of the outer function in giving you the local/protected variable you need.
Of course this has the downside of only giving you one closure instance per definition/generator, instead of letting you call the generator multiple times to get multiple instances. But in many cases you just want one instance anyhow.
P.S. The slides & code examples for the closure presentation will be up on the web site by tomorrow(ish). https://muug.ca/meetings/24-25.html#apr
#!/bin/perl -w
my $inc;
{ my $counter=0;
$inc=sub { $counter++; print "$counter\n"; };
}
$inc->(); $inc->(); $inc->();
print "$counter\n";
# Alberto shields up! _______________________________________________ Roundtable mailing list -- roundtable@muug.ca To unsubscribe send an email to roundtable-leave@muug.ca
I've updated the muug.ca/meetings page, to include the slides (in both ODP and PDF formats), as well as Trevor's sample PHP scripts.
Gilbert
On 2025-04-02 5:11 p.m., Trevor Cordes wrote:
It dawned on me that in perl you can create a closure without even nesting functions (though you can also do it the "traditional" way). Perl allows you to have unnamed blocks that define their own variable scope, which can take the place of the outer function in giving you the local/protected variable you need.
Of course this has the downside of only giving you one closure instance per definition/generator, instead of letting you call the generator multiple times to get multiple instances. But in many cases you just want one instance anyhow.
P.S. The slides & code examples for the closure presentation will be up on the web site by tomorrow(ish). https://muug.ca/meetings/24-25.html#apr
#!/bin/perl -w
my $inc;
{ my $counter=0;
$inc=sub { $counter++; print "$counter\n"; };
}
$inc->(); $inc->(); $inc->();
print "$counter\n";
# Alberto shields up!
-- Gilbert Detillieux E-mail: Gilbert.Detillieux@umanitoba.ca Computer Science Web: http://www.cs.umanitoba.ca/~gedetil/ University of Manitoba Phone: 204-474-8161 Winnipeg MB CANADA R3T 2N2 For best CS dept. service, contact cs-support@lists.umanitoba.ca.
_______________________________________________ Roundtable mailing list -- roundtable@muug.ca To unsubscribe send an email to roundtable-leave@muug.ca