# ! perl -slw use strict; sub nForS(&$@) { my $code = shift; die "First argument must be a code ref" unless ref( $code ) eq 'CODE'; my $aref = shift; die "second argument must be an array ref" unless ref( $aref ) eq 'ARRAY'; my @limits = @_; our @indices; local *indices = $aref; @indices = ( 0 ) x @limits unless @indices; for( my $i = $#limits; $i >= 0; ) { $i = $#limits; $code->( @indices ), ++$indices[ $i ] while $indices[ $i ] < $limits[ $i ]; $i = $#limits; $indices[ $i ] = 0, ++$indices[ --$i ] while $i >= 0 and $indices[ $i ] == $limits[ $i ]; } } my @state; my $n = 10; nForS{ print "@_\n"; last unless --$n } \@state, 3, 6, 9; print "First 10 permutations; enter to see the rest"; ; nForS{ print "@_\n"; } \@state, 3, 6, 9;