Simple showing of file processing in Perl

Friday, September 06, 2013 » programming

Today I had to create script in Perl that processing quite long textbased files and convert new ones. Because sometime it takes long time I wanted to give some information to the script-user how many percent is executed of input file by script. I wanted a simple solution (and do not take the implementation more than 20 minutes including the googling) so just update the percentage on terminal window always in the same line.
Damn simple but informative!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#!/usr/local/bin/perl
..
my $InpFil = $ARGV[0];
my $g_num_of_lines = `wc -l <$InpFile`; #the number of lines in input file   
my $g_cur_of_lines = 0;                 #current line during processing
my $g_cur = 0;
..
open (IN, $InpFile);
while(<IN>){
    ...
    ...
    displayPercent();
}
close(IN);
...
...
sub displayPercent{

  if(eof(IN)){
    print "Processing is done.\n";
  }else{

    #percent calculation and round numbers to be remained on the same place   
    $g_cur = sprintf("%.2f", ($g_cur_of_lines++ / $g_num_of_lines)*100); 

    #refreshing and '\r' get to start of current line
    print "$g_cur %\r";

  }
}