newbio has asked for the wisdom of the Perl Monks concerning the following question:
However, I do not know how to handle variable number of elements in @arrayindex, because the above code is rigid and can only work for exactly two elements in @arrayindex (such as @arrayindex=(3,1)). I want the code to be generic so that it can handle any number of elements in @arrayindex, such as, @arrayindex=(3,0,1), @arrayindex=(3,1), @arrayindex=(4,2,1,5), or @arrayindex=(2) etc. Please advise how this can be done. My thinking here was to create the number of foreach loops dynamically, however, don't know if that is even possible. Thank you guys, Rajmy @array=(['john','tom','peter'],['rose','teak'],['car','truck','jeep +'],['trees','plants'],['good','bad','ugly']); my @arrayindex=(3,1); my %hash=(); foreach my $i (@{$array[$arrayindex[0]]}) { foreach my $j (@{$array[$arrayindex[1]]}) { $hash{"$i $j"}=1; } } foreach my $i (keys %hash) { print "$i=>$hash{$i}\n"; } The output of the program is a hash whose keys represent all possible +combination of values: trees rose=>1; trees teak=>1; plants rose=>1; plants teak=>1;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Advice on loops
by merlyn (Sage) on May 03, 2007 at 15:27 UTC | |
|
Re: Advice on loops
by liverpole (Monsignor) on May 03, 2007 at 16:15 UTC | |
by newbio (Beadle) on May 03, 2007 at 17:50 UTC | |
by shigetsu (Hermit) on May 03, 2007 at 17:55 UTC | |
by newbio (Beadle) on May 06, 2007 at 22:44 UTC | |
|
Re: Advice on loops (A::L::NestedLoops)
by tye (Sage) on May 03, 2007 at 17:48 UTC | |
|
Re: Advice on loops
by parv (Parson) on May 03, 2007 at 22:22 UTC |