File Coverage

blib/lib/String/Sprintf.pm
Criterion Covered Total %
statement 26 29 89.6
branch 7 12 58.3
condition 7 11 63.6
subroutine 5 5 100.0
pod 2 2 100.0
total 47 59 79.6


line stmt bran cond sub pod time code
1             package String::Sprintf;
2 5     5   647866 use strict;
  5         13  
  5         269  
3 5     5   64 use Carp;
  5         12  
  5         535  
4              
5 5     5   43 use vars qw($VERSION);
  5         11  
  5         3248  
6             $VERSION = '1.004';
7              
8              
9             sub formatter { # constructor
10 7     7 1 1103781 my $class = shift;
11 7 50       46 (@_ % 2) and croak "Odd number of arguments";
12 7         29 my %handler = @_;
13 7   50     62 $handler{'*'} ||= 'sprintf'; # default
14              
15             # sanity check
16 7         13 my @errors;
17 7         36 while(my($k, $v) = each %handler) {
18 11 50 66     158 UNIVERSAL::isa($v, 'CODE')
      66        
19             or !defined $v
20             or $v eq 'sprintf'
21             or push @errors, $k;
22             }
23 7 50       30 if(@errors) {
24 0         0 my $errors = join ', ', @errors;
25 0 0       0 my($s, $have) = @errors == 1 ? ('', 'has') : ('s', 'have');
26 0         0 croak "Format$s $errors $have no CODE ref as a handler";
27             }
28 7         42 return bless \%handler, $class;
29             }
30              
31             sub sprintf {
32 8     8 1 2627 my($self, $string, @values) = @_;
33 8         19 my $i = 0;
34 8         74 $string =~ s(\%(?:\%|([+\-\d.]*)([a-zA-Z]))){
35 11 100       93 $2 ? do {
36 10 100 66     65 if(ref(my $handler = $self->{$2} || $self->{'*'})) {
37 6         26 $handler->($1, $values[$i++], \@values, $2);
38             } else {
39 4         58 CORE::sprintf("%$1$2", $values[$i++]);
40             }
41             } : '%'
42             }ge;
43 8         139 return $string;
44             }
45              
46             42;
47              
48             __END__