phaedo has asked for the wisdom of the Perl Monks concerning the following question:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: printing a running count
by monarch (Priest) on Sep 16, 2005 at 04:34 UTC | |
Using the mod (or %) operator takes the remainder after dividing the given number. So, in this case, taking the remainder after dividing $counter by five is what we want. When the remainder is zero we have every 5th object. Printing a number with the \r code instructs the terminal to move the cursor to the beginning of the line without overwriting or going to a new line. | [reply] [d/l] [select] |
|
Re: printing a running count
by McDarren (Abbot) on Sep 16, 2005 at 04:48 UTC | |
Here is one way to do it:
Update: The counter in that code is redundant, so I've edited it. Thanks, [id://fishbot_v2] :) -- Darren | [reply] [d/l] |
|
Re: printing a running count
by liverpole (Monsignor) on Sep 16, 2005 at 12:14 UTC | |
Every time the index variable $i reaches a multiple of $interval (which is 10 in the above program), the line: causes a count to be displayed, along with the total. The escape sequence "\e[K" erases to the end of the line, and the carriage-return "\r" repositions the cursor at the beginning of the line (which is why I recommend pussing the extra space before the word "Progress"). At the end of the loop, don't forget to rewrite the progress, but this time with "\n" to finally go to a new line. You can change the output to your liking; from displaying only the count (with no label) to displaying the percentage complete (eg. printf " Progress %7.3f%%", 100 * $i / $total;"), etc. | [reply] [d/l] [select] |
|
Re: printing a running count
by gargle (Chaplain) on Sep 16, 2005 at 06:43 UTC | |
Hi, update: it's modulus and not modules! I recommend the modulus trick of course, but, just to prove TIMTOWTDI:
So for twenty lines we print four dots (each fifth line).
-- if ( 1 ) { $postman->ring() for (1..2); } | [reply] [d/l] |
|
Re: printing a running count
by liverpole (Monsignor) on Sep 16, 2005 at 14:07 UTC | |
You simply create the meter object with my $meter = new meter($total), call it within the loop with $meter->update($i), and finish up by calling it with no arguments $meter->update() (to show 100% completion, and display the final newline). Update: Added auto-flush of STDERR to the package. Here's the code:
| [reply] [d/l] |
|
Re: printing a running count
by radiantmatrix (Parson) on Sep 16, 2005 at 16:12 UTC | |
I'm assuming you don't know the final count of operations? If you do, check out Term::ProgressBar, which will even give you an ETA. ;-) Otherwise:
<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P) The Code that can be seen is not the true Code "In any sufficiently large group of people, most are idiots" - Kaa's Law | [reply] [d/l] |