Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Perl & modulus

by jkva (Chaplain)
on Feb 15, 2005 at 09:28 UTC ( #431076=perlquestion: print w/replies, xml ) Need Help??
jkva has asked for the wisdom of the Perl Monks concerning the following question:

Wise ones, I am asking this here, for I am starting to dislike asking questions in the CB. Plus, this way, other people can read the answer to this post, which is less selfish if you ask me :)

My question is : I am trying to perform a loop using modulus in my perl script. Is this even possible? I have searched PM and did not find.

My gratitude.


Oh, before I forget... does anyone know how I can "test" if a number is dividable by another number? (As in 9 is dividable by 3, but not by 5)?

Replies are listed 'Best First'.
Re: Perl & modulus
by K_M_McMahon (Hermit) on Feb 15, 2005 at 09:37 UTC
    What kind of loop are you trying to perform?
    This modulus loop runs, hope this gets you in the right direction:
    my $i=99; while (($i%5)!=0) { print "$i not evenly divisible by 5.\n"; $i--; }

    my $a='62696c6c77667269656e6440676d61696c2e636f6d'; while ($a=~m/(^.{2})/s) {print unpack('A',pack('H*',"$1"));$a=~s/^.{2}//s;}
Re: Perl & modulus
by gaal (Parson) on Feb 15, 2005 at 09:37 UTC
    What kind of loop are you trying to perform that you think you need a module for? e.g., Perl has a few looping constructs built into it; can you say what you're missing in them? (Yes, there are modules for loops but you don't reach out for the railgun when the banana peel suffices.) Ah, you really did mean modulus. Sorry, I don't understand the question. What does looping using modulus mean?

    To check if a number $num is divisible by $divisor, use the modulus operator, %:

    if ($num % $divisor) { # does not divide cleanly } else { # does. }
Re: Perl & modulus
by jkva (Chaplain) on Feb 15, 2005 at 09:42 UTC
    Exactly what I needed. Thank you!

    I am trying to perform a loop, it counts from 0 to $i, and it should do something every $x times, while still looping. Modulus is what I needed.

    I just didn't know it was the solution to both of my questions :)


      Here is a nice chunk of code that uses modulus to control looping:
      my ($returnNum) = 0; for my $block (@blocks) { printf ("%-15s ", $block); print "\n" unless (++$returnNum % 5); } print "\n";

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://431076]
Approved by jbrugger
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (11)
As of 2017-01-17 16:23 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (158 votes). Check out past polls.