1 package namespace::clean;
5 namespace::clean - Keep imports and functions out of your namespace
12 use vars qw( $VERSION $STORAGE_VAR $SCOPE_HOOK_KEY $SCOPE_EXPLICIT );
13 use Symbol qw( qualify_to_ref gensym );
14 use B::Hooks::EndOfScope;
15 use Sub::Identify qw(sub_fullname);
16 use Sub::Name qw(subname);
25 $STORAGE_VAR = '__NAMESPACE_CLEAN_STORAGE';
33 use Carp qw(croak); # 'croak' will be removed
35 sub bar { 23 } # 'bar' will be removed
37 # remove all previously defined functions
40 sub baz { bar() } # 'baz' still defined, 'bar' still bound
42 # begin to collection function names from here again
45 sub quux { baz() } # 'quux' will be removed
47 # remove all functions defined after the 'no' unimport
50 # Will print: 'No', 'No', 'Yes' and 'No'
51 print +(__PACKAGE__->can('croak') ? 'Yes' : 'No'), "\n";
52 print +(__PACKAGE__->can('bar') ? 'Yes' : 'No'), "\n";
53 print +(__PACKAGE__->can('baz') ? 'Yes' : 'No'), "\n";
54 print +(__PACKAGE__->can('quux') ? 'Yes' : 'No'), "\n";
60 =head2 Keeping packages clean
62 When you define a function, or import one, into a Perl package, it will
63 naturally also be available as a method. This does not per se cause
64 problems, but it can complicate subclassing and, for example, plugin
65 classes that are included via multiple inheritance by loading them as
68 The C<namespace::clean> pragma will remove all previously declared or
69 imported symbols at the end of the current package's compile cycle.
70 Functions called in the package itself will still be bound by their
71 name, but they won't show up as methods on your class or instances.
73 By unimporting via C<no> you can tell C<namespace::clean> to start
74 collecting functions for the next C<use namespace::clean;> specification.
76 You can use the C<-except> flag to tell C<namespace::clean> that you
77 don't want it to remove a certain function or method. A common use would
78 be a module exporting an C<import> method along with some functions:
80 use ModuleExportingImport;
81 use namespace::clean -except => [qw( import )];
83 If you just want to C<-except> a single sub, you can pass it directly.
84 For more than one value you have to use an array reference.
86 =head2 Explicitely removing functions when your scope is compiled
88 It is also possible to explicitely tell C<namespace::clean> what packages
89 to remove when the surrounding scope has finished compiling. Here is an
95 # blessed NOT available
98 use Scalar::Util qw( blessed );
99 use namespace::clean qw( blessed );
102 return blessed shift;
105 # blessed NOT available
109 When using C<namespace::clean> together with L<Moose> you want to keep
110 the installed C<meta> method. So your classes should look like:
114 use namespace::clean -except => 'meta';
117 Same goes for L<Moose::Role>.
119 =head2 Cleaning other packages
121 You can tell C<namespace::clean> that you want to clean up another package
122 instead of the one importing. To do this you have to pass in the C<-cleanee>
125 package My::MooseX::namespace::clean;
128 use namespace::clean (); # no cleanup, just load
131 namespace::clean->import(
132 -cleanee => scalar(caller),
137 If you don't care about C<namespace::clean>s discover-and-C<-except> logic, and
138 just want to remove subroutines, try L</clean_subroutines>.
142 You shouldn't need to call any of these. Just C<use> the package at the
147 =head2 clean_subroutines
149 This exposes the actual subroutine-removal logic.
151 namespace::clean->clean_subroutines($cleanee, qw( subA subB ));
153 will remove C<subA> and C<subB> from C<$cleanee>. Note that this will remove the
154 subroutines B<immediately> and not wait for scope end. If you want to have this
155 effect at a specific time (e.g. C<namespace::clean> acts on scope compile end)
156 it is your responsibility to make sure it runs at that time.
160 my $RemoveSubs = sub {
166 my $fq = "${cleanee}::$f";
168 # ignore already removed symbols
169 next SYMBOL if $store->{exclude}{ $f };
172 next SYMBOL unless exists ${ "${cleanee}::" }{ $f };
174 if (ref(\${ "${cleanee}::" }{ $f }) eq 'GLOB') {
175 # convince the Perl debugger to work
176 # it assumes that sub_fullname($sub) can always be used to find the CV again
177 # since we are deleting the glob where the subroutine was originally
178 # defined, that assumption no longer holds, so we need to move it
179 # elsewhere and point the CV's name to the new glob.
181 if ( sub_fullname($sub) eq $fq ) {
182 my $new_fq = "namespace::clean::deleted::$fq";
183 subname($new_fq, $sub);
189 # keep original value to restore non-code slots
190 { no warnings 'uninitialized'; # fix possible unimports
191 *__tmp = *{ ${ "${cleanee}::" }{ $f } };
192 delete ${ "${cleanee}::" }{ $f };
196 # restore non-code slots to symbol.
197 # omit the FORMAT slot, since perl erroneously puts it into the
198 # SCALAR slot of the new glob.
199 for my $t (qw( SCALAR ARRAY HASH IO )) {
200 next SLOT unless defined *__tmp{ $t };
201 *{ "${cleanee}::$f" } = *__tmp{ $t };
205 # A non-glob in the stash is assumed to stand for some kind
206 # of function. So far they all do, but the core might change
207 # this some day. Watch perl5-porters.
208 delete ${ "${cleanee}::" }{ $f };
213 sub clean_subroutines {
214 my ($nc, $cleanee, @subs) = @_;
215 $RemoveSubs->($cleanee, {}, @subs);
220 Makes a snapshot of the current defined functions and installs a
221 L<B::Hooks::EndOfScope> hook in the current scope to invoke the cleanups.
226 my ($pragma, @args) = @_;
228 my (%args, $is_explicit);
233 if ($args[0] =~ /^\-/) {
234 my $key = shift @args;
235 my $value = shift @args;
236 $args{ $key } = $value;
244 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
247 $RemoveSubs->($cleanee, {}, @args);
252 # calling class, all current functions and our storage
253 my $functions = $pragma->get_functions($cleanee);
254 my $store = $pragma->get_class_store($cleanee);
256 # except parameter can be array ref or single value
257 my %except = map {( $_ => 1 )} (
259 ? ( ref $args{ -except } eq 'ARRAY' ? @{ $args{ -except } } : $args{ -except } )
263 # register symbols for removal, if they have a CODE entry
264 for my $f (keys %$functions) {
265 next if $except{ $f };
266 next unless $functions->{ $f }
267 and *{ $functions->{ $f } }{CODE};
268 $store->{remove}{ $f } = 1;
271 # register EOF handler on first call to import
272 unless ($store->{handler_is_installed}) {
274 $RemoveSubs->($cleanee, $store, keys %{ $store->{remove} });
276 $store->{handler_is_installed} = 1;
285 This method will be called when you do a
289 It will start a new section of code that defines functions to clean up.
294 my ($pragma, %args) = @_;
296 # the calling class, the current functions and our storage
297 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
298 my $functions = $pragma->get_functions($cleanee);
299 my $store = $pragma->get_class_store($cleanee);
301 # register all unknown previous functions as excluded
302 for my $f (keys %$functions) {
303 next if $store->{remove}{ $f }
304 or $store->{exclude}{ $f };
305 $store->{exclude}{ $f } = 1;
311 =head2 get_class_store
313 This returns a reference to a hash in a passed package containing
314 information about function names included and excluded from removal.
318 sub get_class_store {
319 my ($pragma, $class) = @_;
321 return \%{ "${class}::${STORAGE_VAR}" };
326 Takes a class as argument and returns all currently defined functions
327 in it as a hash reference with the function name as key and a typeglob
328 reference to the symbol as value.
333 my ($pragma, $class) = @_;
336 map { @$_ } # key => value
337 grep { *{ $_->[1] }{CODE} } # only functions
338 map { [$_, qualify_to_ref( $_, $class )] } # get globref
339 grep { $_ !~ /::$/ } # no packages
340 do { no strict 'refs'; keys %{ "${class}::" } } # symbol entries
346 C<namespace::clean> will clobber any formats that have the same name as
347 a deleted sub. This is due to a bug in perl that makes it impossible to
348 re-assign the FORMAT ref into a new glob.
350 =head1 IMPLEMENTATION DETAILS
352 This module works through the effect that a
354 delete $SomePackage::{foo};
356 will remove the C<foo> symbol from C<$SomePackage> for run time lookups
357 (e.g., method calls) but will leave the entry alive to be called by
358 already resolved names in the package itself. C<namespace::clean> will
359 restore and therefor in effect keep all glob slots that aren't C<CODE>.
361 A test file has been added to the perl core to ensure that this behaviour
362 will be stable in future releases.
364 Just for completeness sake, if you want to remove the symbol completely,
365 use C<undef> instead.
369 L<B::Hooks::EndOfScope>
371 =head1 AUTHOR AND COPYRIGHT
373 Robert 'phaylon' Sedlacek C<E<lt>rs@474.atE<gt>>, with many thanks to
374 Matt S Trout for the inspiration on the whole idea.
378 This program is free software; you can redistribute it and/or modify
379 it under the same terms as perl itself.
384 'Danger! Laws of Thermodynamics may not apply.'