http://www.perlmonks.org?node_id=402053

semio has asked for the wisdom of the Perl Monks concerning the following question:

fellow monks,

As a personal exercise, I am interested in building a script that will generate all possible combinations of a defined set of characters. The string length is a user provided option. I put together a solution to this problem; although it works, I believe there is a better way to accomplish the desired result. As an example, here's what I've come up with.

#!perlenv -w use strict; if($#ARGV <1) { print <<EOF; usage: char-gen <charSetNum> <stringLength> charSetNum 1 = a b c charSetNum 2 = a b c 1 2 3 charSetNum 3 = a b c 1 2 3 ! @ # EOF die(); } my @charsSetOne = qw/ a b c /; my @charsSetTwo = qw/ a b c 1 2 3 /; my @charsSetThree = split // , q'abc123!@#'; my @chars; if ( $ARGV[0] == 1) { @chars = @charsSetOne; } elsif ( $ARGV[0] == 2) { @chars = @charsSetTwo; } elsif ( $ARGV[0] == 3) { @chars = @charsSetThree; } my @charsOne = @chars; my @charsTwo = @chars; my @charsThree = @chars; my $charsOne; my $charsTwo; my $charsThree; my @charSetNum = $ARGV[0]; my $stringLength = $ARGV[1]; if ( $stringLength >= 1) { for $charsOne (@charsOne) { print $charsOne . "\n"; } } if ( $stringLength >= 2) { foreach $charsOne (@charsOne) { foreach $charsTwo (@charsTwo) { print $charsOne; print $charsTwo . "\n"; } } } if ($stringLength >= 3) { foreach $charsOne (@charsOne) { foreach $charsTwo (@charsTwo) { foreach $charsThree (@charsThree) { print $charsOne; print $charsTwo; print $charsThree . "\n"; } } } }
My concern is with how I'm handling the user provided option for stringLength. In this example, I'm building nested foreach loops to handle the stringLength option. My question is: how would others approach this? As always, comments, critiques and suggestions for improvement are always welcome.

cheers, semio