Perl: the Markov chain saw PerlMonks

### Perl & modulus

by jkva (Chaplain)
 on Feb 15, 2005 at 09:28 UTC 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.

Detonite

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--;
}

-Kevin
```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 :)

Detonite

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";

Create A New User
Node Status?
node history
Node Type: perlquestion [id://431076]
Approved by jbrugger
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2018-01-23 05:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (238 votes). Check out past polls.

Notices?