http://qs321.pair.com?node_id=378402


in reply to Generate sequential array element combos

Here's a clever, yet impractical, solution. It combines the eye-popping memory growth of tye's first solution, with the incomprensibility of string building.

Anyway, glob() can do this pretty handily, the problem is you need to build the string it uses first:

use strict; use warnings; # setup bounds my @digits = ( 0 .. 9 ); my $min_digits = 4; my $max_digits = 6; # build the glob string my $glob_string; for my $dignum ( 1 .. $max_digits ) { if ( $dignum <= $max_digits - $min_digits ) { $glob_string .= '{' . join( ',', ( '', @digits ) ) . '}'; } else { $glob_string .= '{' . join( ',', @digits ) . '}'; } } # print the permutations my $num; while ( $num = glob( $glob_string ) ) { print $num, "\n"; }
$glob_string ends up looking like (split into two lines for better wrapping):
{,0,1,2,3,4,5,6,7,8,9}{,0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}
{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}
which glob uses to do the work.

I'll note that I was surprised by the memory consumption because in scalar context, glob is a simple iterator. But I suppose it builds all the matches up first and then iterates through them, instead of building them as it goes.