Field of Science

Who knew that 'while' loops can't be nested...

Substantial progress on the Perl model of USS evolution.

First the undergrad and I added the code that tallies up the scores of every sliding-window position in the genome. It didn't take us long to get it running (a few stray semicolons, etc.) However after now Keith's comment on yesterday's post I think there are more efficient ways to do what we've done.

Then we created code that does the recombination a completely different way, so each of the fragments being tested has its own chance to recombine (probability of recombination depends on its score). The code wasn't tricky, but getting it running took ages of tracking down stray curly brackets and discovering that I can't nest two 'while' loops (I changed one of them to an internal 'if' test).

I still need to add in the feature I came up with yesterday, that writes out the genome sequence and the tally of scores only at specified intervals, but now I have to dash off to a 'visioning education' meeting imposed on us by the administration.


  1. It's hard to diagnose the code without seeing it but in principle, nothing prevents nested while() loops. A couple of common "gotchas":

    1. Infinite loops. This often happens when using while() to find a regex and forgetting the 'g' switch. For example to find all occurences of 'ATCG' in string $seq:

    while($seq =~/ATCG/g)

    This would run forever if you forgot the 'g'.

    2. As soon as one while() test is no longer true, the loop will exit to the next (one higher) level of the nest. If the first while() test in the nest is not true, none of the inner while() loops will run. In other words, it's good to know what you expect from each while() test.

    On the curly brackets problem: it really helps if you use an editor that highlights and validates Perl (or any other language). For example there's an emacs perl mode: if you position the cursor next to a bracket, it will highlight that bracket and its partner. I'm sure there are many Mac editors with the same function.

    When writing loops it's good to type all of the opening + closing brackets when you start, before the loop contents. Also align matching opening/closing pairs so as they are below each other in the same column - makes it easier to see which belong with which.

  2. Yes, Neil's right; nested while loops are allowed in Perl, but typos, pastos, or thinkos can break any code.

    Short (valid) sample:
    #!/usr/bin/perl -w
    use strict;

    my $a=0;

    while ($a<15) {
    print "Outer a: $a\n";
    while ($a<10) {
    print "Inner a: $a\n";


Markup Key:
- <b>bold</b> = bold
- <i>italic</i> = italic
- <a href="">FoS</a> = FoS