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


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:

foreach my $con ( @consonants ) { foreach my $vow ( @vowels ) { .. } }
and if the command line argument is CVCCVC, you loop as such:
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 ) { ... } } } } } }
is that correct?

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

    See Algorithm::Loops::NestedLoops(). It knows how to be an iterator and so need never "blow the stack" even if you give it so much work that it could never be done before the sun burns out.

    - tye        

Re^2: variables from STDIN
by stigmatt (Initiate) on Feb 24, 2012 at 15:47 UTC

    Thank you very much for the advice and for the code. You are right, the recursion can sometimes be fastidious with a bigger data input. Actually, there are lots of syllable checkers and hyphenators over there, but as far as I know none of them can help to define all possible syllable structures in a not predefined language.

    And thanks to everybody intersted in the question. All your ideas are very helpful.