1 package Package::Stash;
6 use Scalar::Util qw(reftype);
10 Package::Stash - routines for manipulating stashes
14 my $stash = Package::Stash->new('Foo');
15 $stash->add_package_symbol('%foo', {bar => 1});
17 $stash->has_package_symbol('$foo') # false
18 my $namespace = $stash->namespace;
19 *{ $namespace->{foo} }{HASH} # {bar => 1}
23 Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
24 incredibly messy, and easy to get wrong. This module hides all of that behind a
27 NOTE: Most methods in this class require a variable specification that includes
28 a sigil. If this sigil is absent, it is assumed to represent the IO slot.
34 =head2 new $package_name
36 Creates a new C<Package::Stash> object, for the package given as the only
44 return bless { 'package' => $namespace }, $class;
49 Returns the name of the package that this object represents.
54 return $_[0]->{package};
59 Returns the raw stash itself.
65 # because of issues with the Perl API
66 # to the typeglob in some versions, we
67 # need to just always grab a new
68 # reference to the hash here. Ideally
69 # we could just store a ref and it would
70 # Just Work, but oh well :\
72 return \%{$_[0]->name . '::'};
84 sub _deconstruct_variable_name {
85 my ($self, $variable) = @_;
87 (defined $variable && length $variable)
88 || confess "You must pass a variable name";
90 my $sigil = substr($variable, 0, 1, '');
92 if (exists $SIGIL_MAP{$sigil}) {
93 return ($variable, $sigil, $SIGIL_MAP{$sigil});
96 return ("${sigil}${variable}", '', $SIGIL_MAP{''});
101 =head2 add_package_symbol $variable $value %opts
103 Adds a new package symbol, for the symbol given as C<$variable>, and optionally
104 gives it an initial value of C<$value>. C<$variable> should be the name of
105 variable including the sigil, so
107 Package::Stash->new('Foo')->add_package_symbol('%foo')
109 will create C<%Foo::foo>.
111 Valid options (all optional) are C<filename>, C<first_line_num>, and
114 C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
115 be used to indicate where the symbol should be regarded as having been defined.
116 Currently these values are only used if the symbol is a subroutine ('C<&>'
117 sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
118 hash is updated to record the values of C<filename>, C<first_line_num>, and
119 C<last_line_num> for the subroutine. If these are not passed, their values are
120 inferred (as much as possible) from C<caller> information.
122 This is especially useful for debuggers and profilers, which use C<%DB::sub> to
123 determine where the source code for a subroutine can be found. See
124 L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
125 information about C<%DB::sub>.
129 sub _valid_for_type {
131 my ($value, $type) = @_;
132 if ($type eq 'HASH' || $type eq 'ARRAY'
133 || $type eq 'IO' || $type eq 'CODE') {
134 return reftype($value) eq $type;
137 my $ref = reftype($value);
138 return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE';
142 sub add_package_symbol {
143 my ($self, $variable, $initial_value, %opts) = @_;
145 my ($name, $sigil, $type) = ref $variable eq 'HASH'
146 ? @{$variable}{qw[name sigil type]}
147 : $self->_deconstruct_variable_name($variable);
149 my $pkg = $self->name;
152 $self->_valid_for_type($initial_value, $type)
153 || confess "$initial_value is not of type $type";
155 # cheap fail-fast check for PERLDBf_SUBLINE and '&'
156 if ($^P and $^P & 0x10 && $sigil eq '&') {
157 my $filename = $opts{filename};
158 my $first_line_num = $opts{first_line_num};
160 (undef, $filename, $first_line_num) = caller
161 if not defined $filename;
163 my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
165 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
166 $DB::sub{$pkg . '::' . $name} = "$filename:$first_line_num-$last_line_num";
171 no warnings 'redefine', 'misc', 'prototype';
172 *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
175 =head2 remove_package_glob $name
177 Removes all package variables with the given name, regardless of sigil.
181 sub remove_package_glob {
182 my ($self, $name) = @_;
184 delete ${$self->name . '::'}{$name};
187 # ... these functions deal with stuff on the namespace level
189 =head2 has_package_symbol $variable
191 Returns whether or not the given package variable (including sigil) exists.
195 sub has_package_symbol {
196 my ($self, $variable) = @_;
198 my ($name, $sigil, $type) = ref $variable eq 'HASH'
199 ? @{$variable}{qw[name sigil type]}
200 : $self->_deconstruct_variable_name($variable);
202 my $namespace = $self->namespace;
204 return unless exists $namespace->{$name};
206 my $entry_ref = \$namespace->{$name};
207 if (reftype($entry_ref) eq 'GLOB') {
208 if ( $type eq 'SCALAR' ) {
209 return defined ${ *{$entry_ref}{SCALAR} };
212 return defined *{$entry_ref}{$type};
216 # a symbol table entry can be -1 (stub), string (stub with prototype),
217 # or reference (constant)
218 return $type eq 'CODE';
222 =head2 get_package_symbol $variable
224 Returns the value of the given package variable (including sigil).
228 sub get_package_symbol {
229 my ($self, $variable, %opts) = @_;
231 my ($name, $sigil, $type) = ref $variable eq 'HASH'
232 ? @{$variable}{qw[name sigil type]}
233 : $self->_deconstruct_variable_name($variable);
235 my $namespace = $self->namespace;
237 if (!exists $namespace->{$name}) {
238 # assigning to the result of this function like
239 # @{$stash->get_package_symbol('@ISA')} = @new_ISA
240 # makes the result not visible until the variable is explicitly
241 # accessed... in the case of @ISA, this might never happen
242 # for instance, assigning like that and then calling $obj->isa
243 # will fail. see t/005-isa.t
244 if ($opts{vivify} && $type eq 'ARRAY' && $name ne 'ISA') {
245 $self->add_package_symbol($variable, []);
247 elsif ($opts{vivify} && $type eq 'HASH') {
248 $self->add_package_symbol($variable, {});
252 $self->add_package_symbol($variable)
256 my $entry_ref = \$namespace->{$name};
258 if (ref($entry_ref) eq 'GLOB') {
259 return *{$entry_ref}{$type};
262 if ($type eq 'CODE') {
264 return \&{ $self->name . '::' . $name };
272 =head2 get_or_add_package_symbol $variable
274 Like C<get_package_symbol>, except that it will return an empty hashref or
275 arrayref if the variable doesn't exist.
279 sub get_or_add_package_symbol {
281 $self->get_package_symbol(@_, vivify => 1);
284 =head2 remove_package_symbol $variable
286 Removes the package variable described by C<$variable> (which includes the
287 sigil); other variables with the same name but different sigils will be
292 sub remove_package_symbol {
293 my ($self, $variable) = @_;
295 my ($name, $sigil, $type) = ref $variable eq 'HASH'
296 ? @{$variable}{qw[name sigil type]}
297 : $self->_deconstruct_variable_name($variable);
300 # no doubt this is grossly inefficient and
301 # could be done much easier and faster in XS
303 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
304 { sigil => '$', type => 'SCALAR', name => $name },
305 { sigil => '@', type => 'ARRAY', name => $name },
306 { sigil => '%', type => 'HASH', name => $name },
307 { sigil => '&', type => 'CODE', name => $name },
308 { sigil => '', type => 'IO', name => $name },
311 my ($scalar, $array, $hash, $code, $io);
312 if ($type eq 'SCALAR') {
313 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
314 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
315 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
316 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
318 elsif ($type eq 'ARRAY') {
319 $scalar = $self->get_package_symbol($scalar_desc);
320 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
321 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
322 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
324 elsif ($type eq 'HASH') {
325 $scalar = $self->get_package_symbol($scalar_desc);
326 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
327 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
328 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
330 elsif ($type eq 'CODE') {
331 $scalar = $self->get_package_symbol($scalar_desc);
332 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
333 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
334 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
336 elsif ($type eq 'IO') {
337 $scalar = $self->get_package_symbol($scalar_desc);
338 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
339 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
340 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
343 confess "This should never ever ever happen";
346 $self->remove_package_glob($name);
348 $self->add_package_symbol($scalar_desc => $scalar);
349 $self->add_package_symbol($array_desc => $array) if defined $array;
350 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
351 $self->add_package_symbol($code_desc => $code) if defined $code;
352 $self->add_package_symbol($io_desc => $io) if defined $io;
355 =head2 list_all_package_symbols $type_filter
357 Returns a list of package variable names in the package, without sigils. If a
358 C<type_filter> is passed, it is used to select package variables of a given
359 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
364 sub list_all_package_symbols {
365 my ($self, $type_filter) = @_;
367 my $namespace = $self->namespace;
368 return keys %{$namespace} unless defined $type_filter;
371 # or we can filter based on
372 # type (SCALAR|ARRAY|HASH|CODE)
373 if ($type_filter eq 'CODE') {
375 (ref($namespace->{$_})
376 ? (ref($namespace->{$_}) eq 'SCALAR')
377 : (ref(\$namespace->{$_}) eq 'GLOB'
378 && defined(*{$namespace->{$_}}{CODE})));
379 } keys %{$namespace};
381 return grep { *{$namespace->{$_}}{$type_filter} } keys %{$namespace};
389 Please report any bugs through RT: email
390 C<bug-package-stash at rt.cpan.org>, or browse to
391 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
395 L<Class::MOP::Package> - this module is a factoring out of code that used to
400 You can find this documentation for this module with the perldoc command.
402 perldoc Package::Stash
404 You can also look for information at:
408 =item * AnnoCPAN: Annotated CPAN documentation
410 L<http://annocpan.org/dist/Package-Stash>
414 L<http://cpanratings.perl.org/d/Package-Stash>
416 =item * RT: CPAN's request tracker
418 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
422 L<http://search.cpan.org/dist/Package-Stash>
428 Jesse Luehrs <doy at tozt dot net>
430 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
433 =head1 COPYRIGHT AND LICENSE
435 This software is copyright (c) 2010 by Jesse Luehrs.
437 This is free software; you can redistribute it and/or modify it under
438 the same terms as perl itself.