in reply to Running a subroutine a certain number of times

Your bug is caused by serious scoping problems. Because you are not using any scoping or lexical variables. The $i in your outer look is the same variable as the $i in your subroutine.
As long as $leg is greater than $number_of_sequences (and if it is generated using $min_length, it will be), the loop will terminate after one call.
You probably wanted:
$number_of_sequences=12; $max_length=50; $min_length=30; my @set; for (my $i=0; $i < $number_of_sequences;$i++) { my $aminoseq = genseq($aminoseq); print "$aminoseq\n\n"; push (@set,$aminoseq); } sub genseq { my $leg=randomlength(); my $seq; for (my $i=0; $i<$leg; $i++) { $seq.=randomaminoacid(); } return $seq; }
use strict would have caught this and many other problems in your code. Incidently, if the three variables at the top of your code are constant, if would declare them as:
use const NUMBER_OF_SEQUENCES => 12; use const MAX_LENGTH => 50; use const MIN_LENGTH => 30;
That way it is clear that they are constants, and it is impossible to inadvertently change them.
Read the Camel book for more information on scoping and lexical variables.
Hope this helps,

-pete
"Pain heals. Chicks dig scars. Glory lasts forever."

Replies are listed 'Best First'.
Re: Re: Running a subroutine a certain number of times
by davorg (Chancellor) on Aug 05, 2002 at 15:11 UTC

    Also, you almost certainly don't need those old C-style for loops. and actually, you don't need those $i variables at all.

    $number_of_sequences=12; $max_length=50; $min_length=30; my @set; foreach (0 .. $number_of_sequences) { my $aminoseq = genseq($aminoseq); print "$aminoseq\n\n"; push (@set, $aminoseq); } sub genseq { my $leg = randomlength(); my $seq; foreach (0 .. $leg) { $seq .= randomaminoacid(); } return $seq; }
    or even
    sub genseq { my $seq; $seq .= randomaminoacid() foreach 0 .. randomlength(); return $seq; }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

      I definitely agree. I just didn't want to take his code too far astray. Plus, it's really hard to demonstrate scoping problems while removing all the variables that are causing the scoping problems.

      -pete
      "Pain heals. Chicks dig scars. Glory lasts forever."