Next | Tricks of the Wizards | 172 |
sub make_iterator {
my @tokens = split /(\#)/, shift(); my $n_digits = grep {$_ eq '#'} @tokens; my $digits = '0' x $n_digits;
return sub { my $result; my $d = 0; for my $t (@tokens) { if ($t eq '#') { $result .= substr($digits, $d++, 1); } else { $result .= $t; } }
$digits++; if (length $digits > $n_digits) { # Overflow? $digits = '0' x $n_digits; # Reset }
return $result; }; }
Anonymous subroutine is a closure
my variables are caputured by the closure
Each call to make_iterator constructs a new closure with new private state variables
Next | Copyright © 2003 M. J. Dominus |