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


In reply to character generator by semio

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.