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

I am using a for loop to get all the numbers divisible by 5 over 0 to 20(just a random num for now) but I don't understand the behavior now...please explain what i am not seeing

ultimately, I want to find all the number divisible by even numbers over a range of 0 to 10

use strict; use warnings; use integer; use constant number => 5; my %result; for ( my $i=0; $i<=20 ;$i++){ print $i%5,"\n"; #here to test for % at even numbers }

output

0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0

Replies are listed 'Best First'.
Re: why is my for loop using modulo giving me a weird output
by Corion (Patriarch) on Jun 28, 2015 at 06:55 UTC

    What other output did you expect?

    Maybe it helps you to tell us (in English) what the modulo operator returns and how that relates to a number being evenly divisible.

      first, I tried with five just to check out how modulo worked

      nothing to do with even number yet. this is a incremental test code for me to learn perl code

      I expected the output to look like this:

      1 2 3 4

      this is because as I go thru the for loop, I goes thru 1,2,3,4,5,6,7,8,9,10,...,15,...20

      but the for loop returns "0" 1 2 3 4( not as expected with "0") then it gives me the same output another 4 times. I don't understand the output being given 4 times.

      sorry for not being clearer

      perhaps this helps explain my question on iteration

        I tried with five just to check out how modulo worked

        https://en.wikipedia.org/wiki/Modulo_operation

        I expected the output to look like this:

        1 2 3 4

        Why? Modulo is the remainder of the division. 0 divided by 5 is 0, remaining 0. 1 divided by 5 is 0, remaining 1. 2 divided by 5 is 0, remaining 2. 3 divided by 5 is 0, remaining 3. 4 divided by 5 is 0, remaining 4. 5 divided by 5 is 1, remaining 0. 6 divided by 5 is 1, remaining 1. And so on.

        Alexander

        --
        Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

        Please read Corion again!

        Is there difference between printing, what modulo operator returns and using it to test?

        i.e

        print 4%2; # or if (4%2 == 0) { # blah..blah... }
        Is there a difference?

        If you tell me, I'll forget.
        If you show me, I'll remember.
        if you involve me, I'll understand.
        --- Author unknown to me
Re: why is my for loop using modulo giving me a weird output
by GrandFather (Saint) on Jun 28, 2015 at 12:03 UTC

    In Perl your for loop is better written:

    for my $count (0 .. 20) { ... }
    Perl is the programming world's equivalent of English