Next Tricks of the Wizards 172

Iterator Example

        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;
            };
        }


Next Copyright © 2003 M. J. Dominus