blib/lib/MYDan/Util/Percent.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 10 MC/DCmcdc 0.0% 0 / 6 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 5 totaltotal 0.0% 0 / 90 CC 11 SCAR 32.1
CC
11
Cov
0%
print
42.0
_human
30.0
add
6.0
CRAP 24.8
1 package MYDan::Util::Percent;
2 use strict;
3 use warnings;
4  
5 $|++;
6  
7 sub new
8 {
9 my $class = shift;
10 bless +{ size => shift, count => 0, time => 0, speed => '0/s', len => 0, prompt => (shift||''), pcb => shift },
11 ref $class || $class;
12 }
13  
14 sub renew
15 {
16 my $this = shift;
17 $this->{size} = shift;
18 return $this;
19 }
20  
21 sub add
22 {
23 my $this = shift;
24 my $add = shift||1;
25 $this->{len} = $this->{len} + $add;
26 my $time = int time;
27 if( $time eq $this->{time} )
28 {
29 $this->{count} += $add;
30 }
31 else
32 {
33 $this->{speed} = _human(( $this->{count} + $add )/( $time - $this->{time} ));
34 $this->{time} = $time;
35 $this->{count} = 0;
36 }
37 return $this;
38 }
39  
40 sub print
41 {
42 my ( $this, $prompt ) = @_;
43 my ( $size, $len, $pcb ) = @$this{qw( size len pcb )};
44 $prompt ||= $this->{prompt};
45 my $p = $size ? sprintf( "%d", $len*100/$size ) : 0;
46 $p = 100 if $p >100;
47  
48 my $percent = "$prompt $p% ". _human( $len ) ."/".($size ? _human( $size ) : 'unkown' ).' '.$this->{speed}.'/s';
49 if( $pcb )
50 {
51 &$pcb( "$percent" );
52 }
53 else
54 {
55 print "\r$percent".' ' x 20;
56 print "\n" if $p==100;
57 }
58  
59 return $this;
60 }
61  
62 sub _human
63 {
64 my $c = shift;
65 return '1' if $c <= 1;
66 if( $c > 1073741824 )
67 {
68 $c = sprintf "%.1fG", $c / 1073741824;
69 }
70 elsif( $c > 1048576 )
71 {
72 $c = sprintf "%.1fM", $c / 1048576;
73 }
74 elsif( $c > 1024 )
75 {
76 $c = sprintf "%.1fK", $c / 1024;
77 }
78
79 return $c;
80 }
81  
82 1;
83 __END__