Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

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.

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)?

Comment on Perl & modulus
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";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://431076]
Approved by jbrugger
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2014-12-29 10:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (186 votes), past polls