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

Hello! I was wondering if it's possible to show the percentage of a while loop in perl. The while loops reads a txt file and then processes it, maybe this helps. Thx in advance

Replies are listed 'Best First'.
Re: percentage while loop
by oko1 (Deacon) on Jul 18, 2008 at 14:01 UTC

    Here's a "traditional" sort of counter, with a '.' for every percentage point and numbers at every 10% mark:

    #!/usr/bin/perl -w use strict; $|++; open Fh, "file" or die "file: $!\n"; my $s = -s Fh; my ($last, $total) = 0; while (<Fh>){ $total += length; my $p = int($total * 100 / $s); if ($p != $last){ $last = $p; print STDERR $p % 10 ? "." : "$p%"; } }
    
    -- 
    Human history becomes more and more a race between education and catastrophe. -- HG Wells
    
      Thx, you helped me a lot. It works now.
Re: percentage while loop
by GrandFather (Saint) on Jul 18, 2008 at 12:46 UTC

    Use -s to determine the size of the file. Sum line lengths into a progress counter as the lines are processed. For each progress update divide the progress counter by the file size, multiply to 100, and there's your percentage.


    Perl is environmentally friendly - it saves trees
Re: percentage while loop
by pjotrik (Friar) on Jul 18, 2008 at 12:11 UTC
    The nature of while loop makes it quite difficult. For the task at hand (processing a file line by line), I can come up with few solutions, but none that I would recommend.
    • count lines before the actual processing, i.e. process the file twice. wc -l might help.
    • stat the file to get its size and then count bytes processed.
    Usually, in a console script, I'd settle for printing a dot every few lines.

    UPDATE: As pointed out by GrandFather in a very similar topic today (Estimate line count in text file), you can use tell to detect your position inside the file. That together with detecting the size of the file gives quite a nice solution.

Re: percentage while loop
by Perlbotics (Archbishop) on Jul 18, 2008 at 13:36 UTC
    In case the files you have to process are quite large, I recommend to limit the number of updates of your progress indicator. Maybe 10-100 updates per prcessed file are sufficient? The following snipped will update about 100 times:
    #in the loop # update $percentage, e.g. 100 * $summed_size / $file_size; ... (printf STDERR "Progress: %3d%%\r", $percentage),$lastpercentage=int($ +percentage) if int($percentage) != $lastpercentage; ...
    Last given output might not be '100%'. You might want to force an update at the last iteration (using e.g. eof).
Re: percentage while loop
by apl (Monsignor) on Jul 18, 2008 at 11:28 UTC
Re: percentage while loop
by ambrus (Abbot) on Jul 23, 2008 at 19:23 UTC
Re: percentage while loop
by Anonymous Monk on Jul 18, 2008 at 11:26 UTC
    Its possible, you just print