File Coverage

blib/lib/Sub/Remove.pm
Criterion Covered Total %
statement 43 43 100.0
branch 12 12 100.0
condition 3 3 100.0
subroutine 7 8 87.5
pod 1 1 100.0
total 66 67 98.5


line stmt bran cond sub pod time code
1             package Sub::Remove;
2              
3 3     3   82323 use strict;
  3         13  
  3         77  
4 3     3   11 use warnings;
  3         5  
  3         69  
5              
6 3     3   13 use Carp qw(croak);
  3         5  
  3         205  
7 3     3   19 use Exporter qw(import);
  3         4  
  3         524  
8             our @ISA = qw(Exporter);
9             our @EXPORT_OK = qw(
10             sub_remove
11             );
12              
13             our $VERSION = '0.01';
14              
15       0     sub __placeholder {}
16              
17             sub sub_remove {
18 5     5 1 3273 my ($sub_name, $class) = @_;
19              
20 5 100       15 if (! defined $sub_name) {
21 1         154 croak "sub_remove() requires a subroutine name as parameter";
22             }
23              
24 4 100       8 if (! defined $class) {
25 2         4 $class = 'main';
26             }
27              
28 4 100       29 if (! $class->can($sub_name)) {
29 2         277 croak "Subroutine named '${class}::${sub_name}' doesn't exist";
30             }
31              
32 2         5 my $src;
33              
34             # get the calling package symbol table name
35             {
36 3     3   18 no strict 'refs';
  3         5  
  3         666  
  2         4  
37 2         4 $src = \%{ $class . '::' };
  2         7  
38             }
39              
40             # loop through all symbols in calling package, looking for subs
41 2         44 for my $symbol ( keys %$src ) {
42             # get all code references, make sure they're valid
43 250         211 my $sub = *{ $src->{$symbol} }{CODE};
  250         454  
44 250 100 100     443 next unless defined $sub and defined &$sub;
45              
46             # save all other slots of the typeglob
47 29         29 my @slots;
48              
49 29         37 for my $slot (qw( SCALAR ARRAY HASH IO FORMAT )) {
50 145         131 my $elem = *{ $src->{$symbol} }{$slot};
  145         224  
51 145 100       242 next unless defined $elem;
52 29         41 push @slots, $elem;
53             }
54              
55             # clear out the source glob
56 29         54 undef $src->{$symbol};
57              
58             # replace the sub in the source
59 29 100       69 if ($symbol ne $sub_name) {
60             $src->{$symbol} = sub {
61 4     4   849 my @args = @_;
62 4         10 return $sub->(@_);
63 27         82 };
64             }
65              
66             # replace the other slot elements
67 29         43 for my $elem (@slots) {
68 29         70 $src->{$symbol} = $elem;
69             }
70             }
71             }
72              
73             1;
74             __END__