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

For my Unix class last semester, Perl was briefly introuced and I decided that the assignments were better handled using Perl than Bash. When time came for the final, the extra credit involved figuring out if a number was prime or not, either by calculating it, by looking it up, or both.

I've taken that concept and to try to get my feet wet in Perl, I decided to expand upon it.

My latest script asks for a lower- and upper-bound for calculating, then determines all the primes and outputs it to a file.

I've had a spinner in there previously to show it was working; right now it displays how many primes have been found in X seconds, but I'd like to use a progress bar to show how far along the script is.

I couldn't get Term::ProgressBar to work for me, so I switched to Term::StatusBar.

What I want to have (ideally) is one line showing what I already have (the # of primes found and the elapsed time) and below it, a progress bar. Right now, it's displaying the bar but it stays at 0% and never moves.

#! /usr/bin/perl use Time::HiRes qw(time); use Math::Round 'nlowmult'; use Term::StatusBar; print "Enter the lower bound:\n"; chomp ($low=<>); while ($low < 1) { print "That number is not valid.\n"; print "Enter the lower bound:\n"; chomp ($low = <>); } print "Enter the upper bound:\n"; chomp ($high = <>); while ($high <= $low) { print "That number is not valid.\n"; print "Enter the upper bound:\n"; chomp ($high = <>); } $totalnumber = $high - $low; my $status = new Term::StatusBar ( label => 'Progress: ', totalItems => $totalnumber, startRow => 3, ); system (clear); print "Finding the primes between $low and $high...\n"; $status->start; $total = 0; $timestart = time; open (my $fh, ">>", primes); print $fh "#:Time(s):Result\n"; print $fh "============================\n"; close $fh; for ($i=$low; $i<=$high; $i++) { $is_prime = 1; for ($j=2; $j<=sqrt($i); $j++) { if ($i%$j == 0) { $is_prime = 0; $status->setItems($i); for (1..$_[0]){ sleep 1; $status->update; } break; } } if ($is_prime == 1) { $total++; open (my $fh, ">>", primes); $duration = time - $timestart; print $fh "$total:$duration:$i\n"; close $fh; $duration = nlowmult(0.01, time - $timestart); # print "\rFound $total primes so far in $duration seconds..."; } } print "\n";

Not the most elegant, I'll grant, but I literally started learning this language a month ago. And also, I know there's better ways to determine primes. Again, this is for my own edification. What am I doing wrong here?

Thanks in advance.

Replies are listed 'Best First'.
Re: Using a progress bar... having issues
by 1nickt (Canon) on Aug 08, 2015 at 16:51 UTC

    First, add use strict; and use warnings; to the top of every script you write. It's a free error-checker and it's daft to ignore it. You have lots of uninitialized variables, you are not doing error checking on your function calls, and you are using barewords in the code. You need to fix all that.

    I guess system(clear); and break; are supposed to stop the terminal going wonky; you probably need to use another Term::* module. Also 'clear' and 'break' cannot be unquoted:

    Unquoted string "clear" may clash with future reserved word at 1137927 +.pl line 35. Bareword "break" not allowed while "strict subs" in use at 1137927.pl +line 57. Bareword "clear" not allowed while "strict subs" in use at 1137927.pl +line 35.

    But the problem you originally asked about is caused by having copied code from the docs for Term::StatusBar:

    sub doSomething { $status->setItems($_[0]); for (1..$_[0]){ sleep 1; $status->update; ## Will call $status->start() if needed } }

    This is a subroutine that is called earlier in the example like this:

    doSomething(20);

    '20' is passed to the sub as an argument. Perl creates the special array @_ to hold the arguments passed to a sub. So in the example $_[0] is the first element in the array, i.e. the first argument passed, i.e. '20'. So the code says "sleep for one second and repeat once for each number between 1 and 20, then move on (and update the status bar status)".

    Your code has no subroutine and there is no value in @_ or $_[0], so that's not going to work. if you had use warnings; Perl would have told you with the warning: Use of uninitialized value in foreach loop entry at foo.pl, line 52 ... and you could have been led to the problem.

    I got rid of the for loop so that part of your code looks like:

    if ($i % $j == 0) { $is_prime = 0; $status->setItems($i); sleep 1; }

    This makes the bar advance, but there's more to do to get your program running right.

    Advice: as a beginner, do one thing at a time. If you want to learn how to use a progress bar, create a small test script that does nothing else but that. When you copy examples to try out, copy the whole example and run it as is. Only once you have really "got it" should you combine that technique with others.

    Hope this helps!

    Update: added answer

    The way forward always starts with a minimal test.
Re: Using a progress bar... having issues
by poj (Abbot) on Aug 08, 2015 at 19:19 UTC
    I couldn't get Term::ProgressBar to work

    Take a look at this node Term::ProgressBar or try this

    #! /usr/bin/perl use strict; use Term::ProgressBar; my $low = 1; my $high = 20; my $status = Term::ProgressBar->new( { name => 'Progress', count => $high - $low + 1, term_width => 80, }); my $count = 0; for my $no ( $low .. $high ){ # # calc prime # sleep 1; $status->update(++$count); }
    poj
      Not trying to hi-jack the thread, I just slapped this code of yours a modified version of this code above into a byte reverse script I have, and it does work correctly, but it slows it down dramatically. I guess it is all the figuring of the percentages and printing to console. In my tests with Time::HiRes I get times of .02 sec without printing progress bar, and times of .78 sec with progress bar. Any ideas to speed that up? Sorry if I am getting off topic, I just didnt want to make a new thread.

      EDIT: I was able to speed it up to .22 sec with progress bar by adjusting the buffer size.
      EDIT2: Nevermind, I got it back to =~ .1 sec. Though I would like to get it back down to around .02 :P

        For anything taking less than about a second a progress bar is, as you have amply demonstrated, a complete waste of time. As a general thing aim for a progress bar update about every 1/10th of a second. That means having some idea of how long each iteration of your process takes an perform a progress bar update every 1 / (10 * iteration seconds) iterations.

        Premature optimization is the root of all job security