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

Hi all- I'm trying to print some output after every 100 iterations of a large array just to make it known the script is still running and not frozen in the background. I tried
my $cnt = 0; for (0 .. 99999) { $cnt++; if ($cnt%100) { print "$cnt\n"; } }
As a test script and it prints out every single number as far as I can see.
... 32287 32288 32289 32291 ...
Any ideas?

Replies are listed 'Best First'.
Re: Perl modulus not working
by blue_cowdawg (Monsignor) on Aug 22, 2011 at 13:47 UTC

    Looks to me like it is working just fine.  101 % 100 is going to return a non-zero which in Perl is translated to be a true statement. What I think you are looking for is something along the lines of  ($cnt % 100) == 0


    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: Perl modulus not working
by BrowserUk (Patriarch) on Aug 22, 2011 at 13:57 UTC

    You need to invert the condition of your test. Ie:

    unless( $cnt % 100 ) { print "$cnt\n"; }

    If you do not understand why that works, think about it for a while. Try tracing it out on a piece of paper.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Perl modulus not working
by rovf (Priest) on Aug 22, 2011 at 14:25 UTC
    it prints out every single number
    I don't think it printed 32200 ....

    -- 
    Ronald Fischer <ynnor@mm.st>
Re: Perl modulus not working
by ricDeez (Scribe) on Aug 22, 2011 at 17:31 UTC

    Actually, apart from the obvious bug in the code, there are alternative ways of doing what you are attempting to do here. A possible alternative would be to use Damian Conway's Smart:Comments module. See below:

    use Modern::Perl; use Smart::Comments; my $cnt = 0; for (0 .. 999_999) { ### Processing===[%] done $cnt++; sleep(.5); } say "Finished!"

    Now you really need to run this code from the command line to appreciate just how much you get for free when using this module, especially for what you are trying to do...

Re: Perl modulus not working
by locked_user sundialsvc4 (Abbot) on Aug 22, 2011 at 14:07 UTC

    FYI, it is customary to print status-messages to STDERR when output goes to STDOUT.   Output buffering can sometimes also be a consideration (in other contexts).