File Coverage

blib/lib/Dispatch/Declare.pm
Criterion Covered Total %
statement 31 39 79.4
branch 5 10 50.0
condition 0 4 0.0
subroutine 8 10 80.0
pod 4 4 100.0
total 48 67 71.6


line stmt bran cond sub pod time code
1             package Dispatch::Declare;
2              
3 2     2   64807 use warnings;
  2         6  
  2         64  
4 2     2   11 use strict;
  2         3  
  2         69  
5 2     2   14 use Carp;
  2         7  
  2         264  
6              
7             our $VERSION = '0.1.2';
8              
9             sub import {
10 2     2   16 no strict 'refs';
  2         5  
  2         1284  
11 2     2   16 *{ caller() . '::declare' } = \&declare;
  2         12  
12 2         4 *{ caller() . '::declare_once' } = \&declare;
  2         8  
13 2         5 *{ caller() . '::undeclare' } = \&undeclare;
  2         10  
14 2         3 *{ caller() . '::run' } = \&run;
  2         8  
15 2         4 *{ caller() . '::dispatch' } = \&dispatch;
  2         23  
16             }
17              
18             my $stash = {};
19             my $once = {};
20              
21             sub declare($&) {
22 2     2 1 19 my $key = shift;
23 2         4 my $code = shift;
24              
25 2 50 0     9 carp('Cannot modify declare_once field') && return
26             if exists $once->{ uc $key };
27              
28 2         7 $stash->{ uc $key } = $code;
29             }
30              
31             sub undeclare($) {
32 1     1 1 5 my $key = shift;
33              
34 1 50       10 delete $stash->{ uc $key } if exists $stash->{ uc $key };
35             }
36              
37             sub declare_once($&) {
38 0     0 1 0 my $key = shift;
39 0         0 my $code = shift;
40              
41 0 0 0     0 carp('Cannot modify declare_once field') && return
42             if exists $once->{ uc $key };
43 0     0   0 declare $key => sub { $code };
  0         0  
44 0         0 $once->{ uc $key }++;
45              
46 0         0 return 1;
47             }
48              
49             sub run {
50 2     2 1 444 my $key = shift;
51 2 100       15 if ( exists $stash->{ uc $key } ) {
    50          
52 1         6 return $stash->{ uc $key }->(@_);
53             }
54             elsif ( exists $stash->{'DEFAULT'} ) {
55 0           return $stash->{'DEFAULT'}->(@_);
56             }
57             }
58              
59             *dispatch = *run;
60              
61             1; # Magic true value required at end of module
62             __END__