enderk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am fairly new to Perl and Perlmonks so I hope I'm not breaking any rules by posting this message here! I was having a look at some algorithms on Bioperl (http://www.bioperl.org/wiki/Getting_all_k-mer_combinations_of_residues). Basically, out of the four letters 'A', 'T', 'G' and 'C', the following code gives me all the combinations of k-long "words" (so if k = 3, it would produce AAA, AAT, AAG... CCC):

use warnings; use strict; sub kmers { my $k = shift; my $alphabet = qw( A T G C ); my @bases = @$alphabet; my @words = @bases; for ( 1 .. --$k ) { my @newwords; foreach my $w (@words) { foreach my $b (@bases) { push (@newwords, $w.$b); } } @words = @newwords; } return @words; }

I can understand most of this code, but I have trouble understanding how the

for (1 .. --$k)

loop is being implemented. Whenever I've seen these for/foreach loops, once INSIDE the loop, you usually do something with the list of numbers inside the parenthesis (in this case, numbers 1 through 'k minus one'). In this case, I cannot see how the list is being used. I have read the Perldoc entry on foreach loops, but I couldn't find out how this loop works.

Could someone please refer me to a resource/reference that explains how such a loop might be working? Again, I'm sorry if this seems to be too trivial compared to most of the questions asked on this site.

Replies are listed 'Best First'.
Re: How do foreach loops use their list values?
by LanX (Saint) on Nov 02, 2013 at 23:11 UTC
    The value ( i.e. $_) isn't used here, it's just for $k - 1 repetitions.

    FWIW your code is buggy and won't run.

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Thanks a lot for your reply, LanX. That makes sense :)

      Will have a look at the code to see what is wrong

        In particular, consider the statement
            my $alphabet = qw( A T G C );
        and maybe do a little experiment to print  $alphabet and see just what it is.

        Update: The next statement
            my @bases = @$alphabet;
        suggests  $alphabet is supposed to be an array reference that is de-referenced to initialize the  @bases array, but since  $alphabet is used nowhere else, why not just initialize  @bases directly from the  qw(A T G C) list of bases?