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

Hi there, Absolute programming beginner here. Pls how do i get a loop to run a certain number of times and stop. I currently use an array as a counter but i feel there might be a more straightforward way.

Replies are listed 'Best First'.
Re: loopy trouble
by stevieb (Canon) on Jan 07, 2016 at 21:19 UTC

    Here's probably the easiest way...

    for (1..100){ print "$_\n"; }

      For perl 6?

        Exactly the same (note that with perl6, you can omit the parens):

        #!/usr/bin/perl6 for (1..3){ print "$_\n"; }

        ...or, you can use say. (You can in perl5 as well, if you use feature 'say';):

        for (1..3){ say $_; }

        or a shortcut if you're only doing a small task (same as perl5):

        print "$_\n" for 1..3; say $_ for 1..3;
Re: loopy trouble
by jeffa (Bishop) on Jan 07, 2016 at 21:31 UTC

    First you have to answer the question, is the amount of times to loop going to be known ahead of time or will it depend on some condition being met down the road? If the former, you generally use for loops, and you generally use while loops for the latter.

    # find sum of first 100 digits my $sum = 0; for my $i (0 .. 99) { $sum += $i; }

    # print lines from a file handle and stop when done while (my $line = <FILE>) { print $line; }

    If you need to break out of a loop, you can use the last keyword

    for (0 .. 99) { print "$_\n"; last if $_ == 42; }

    Hope this helps!

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)