in reply to More effective way of doing this
Here, the recursive call to add_to_strings is the key for generating arbitrarily nested loops.$ perl -e 'use strict; > use warnings; > > my @array = qw(A T C G); > my $length = 5; > my @result = @array; > > add_to_strings($length - 1); > print "@result"; > > > sub add_to_strings { > my $len = shift; > return if $len <= 0; > my @temp; > for my $string (@result) { > push @temp, $string . $_ for @array; > } > @result = @temp; > add_to_strings ($len - 1); > } > ' AAAAA AAAAT AAAAC AAAAG AAATA (... many string omitted for brevity ... +) GGGGA GGGGT GGGGC GGGGG
You could do it without recursion, but it's likely to be a bit more complicated.
Also note that I have used here a global @result array for simplicity, but you could also pass @result in subroutine calls and returns to make it cleaner.
Update at 15:51 UTC: this is what the cleaner version might look like:
You don't really need the @temp_result here, you could traverse directly @_, I just used @temp_result for better clarity, but this entails quite a bit of extra array copies, which might be inefficient for longer strings.use strict; use warnings; my @array = qw(A T C G); my $length = 5; my @result = add_to_strings($length - 1, @array); print "@result"; sub add_to_strings { my $len = shift; my @temp_result = @_; return @temp_result if $len <= 0; my @temp; for my $string (@temp_result) { push @temp, $string . $_ for @array; } add_to_strings ($len - 1, @temp); }
|
|---|