in reply to variables from STDIN
Interesting ... if I'm reading the OP correctly, you want to create a looping structure that is influenced in two ways by a command line argument: first, the number of loops is controlled by the length of the command line argument; and two, what you're looping is controlled by the command line argument.
So if the command line argument is CV, you loop as such:
and if the command line argument is CVCCVC, you loop as such:foreach my $con ( @consonants ) { foreach my $vow ( @vowels ) { .. } }
is that correct?foreach my $con_1 ( @consonants ) { foreach my $vow_1 ( @vowels ) { foreach my $con_2 ( @consonants ) { foreach my $con_3 ( @consonants ) { foreach my $vow_2 ( @vowels ) { foreach my $con_4 ( @consonants ) { ... } } } } } }
My first reaction is find another way. But if you wish to persist, I think recursion is your frenemy here:
#!/usr/bin/perl my $template = shift || die "usage: $0 <template>\n"; my @pattern = split( //, $template ); my $levels = scalar( @pattern ); my $vowels = [ qw( a e i o u y ) ]; my $consonants = [ qw( b c d f g h j k l m n p q r s t v w x z ) ]; output_cv( 0, \@pattern, $consonants, $vowels, "" ); sub output_cv { my( $level, $pattern, $consonants, $vowels, $string ) = @_; # if we have no more levels in the pattern, output the buffered stri +ng if( $level == scalar( @$pattern ) ) { print "$string\n"; } else { # figure out which array at this pattern level my $array = $pattern->[$level] eq 'C' ? $consonants : $vowels; foreach my $ele ( @$array ) { # start new buffer string my $new_string = $string . $ele; # recurse to next level my $new_level = $level + 1; output_cv( $new_level, $pattern, $consonants, $vowels, $new_stri +ng ); } } }
I say frenemy because the above is a fairly naive implementation and eventually some combination of template size and/or arrays is going to blow the stack.
-derby
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: variables from STDIN (NestedLoops)
by tye (Sage) on Feb 22, 2012 at 14:44 UTC | |
Re^2: variables from STDIN
by stigmatt (Initiate) on Feb 24, 2012 at 15:47 UTC |
In Section
Seekers of Perl Wisdom