1 package Package::Stash;
4 # ABSTRACT: routines for manipulating stashes
7 use Scalar::Util qw(reftype);
12 my $stash = Package::Stash->new('Foo');
13 $stash->add_package_symbol('%foo', {bar => 1});
15 $stash->has_package_symbol('$foo') # false
16 my $namespace = $stash->namespace;
17 *{ $namespace->{foo} }{HASH} # {bar => 1}
21 Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
22 incredibly messy, and easy to get wrong. This module hides all of that behind a
25 NOTE: Most methods in this class require a variable specification that includes
26 a sigil. If this sigil is absent, it is assumed to represent the IO slot.
28 =method new $package_name
30 Creates a new C<Package::Stash> object, for the package given as the only
41 # supposedly this caused a bug in earlier perls, but I can't reproduce
42 # it, so re-enabling the caching
43 $namespace = \%{$package . '::'};
46 'package' => $package,
47 'namespace' => $namespace,
53 Returns the name of the package that this object represents.
58 return $_[0]->{package};
63 Returns the raw stash itself.
68 return $_[0]->{namespace};
80 sub _deconstruct_variable_name {
81 my ($self, $variable) = @_;
83 (defined $variable && length $variable)
84 || confess "You must pass a variable name";
86 my $sigil = substr($variable, 0, 1, '');
88 if (exists $SIGIL_MAP{$sigil}) {
89 return ($variable, $sigil, $SIGIL_MAP{$sigil});
92 return ("${sigil}${variable}", '', $SIGIL_MAP{''});
97 =method add_package_symbol $variable $value %opts
99 Adds a new package symbol, for the symbol given as C<$variable>, and optionally
100 gives it an initial value of C<$value>. C<$variable> should be the name of
101 variable including the sigil, so
103 Package::Stash->new('Foo')->add_package_symbol('%foo')
105 will create C<%Foo::foo>.
107 Valid options (all optional) are C<filename>, C<first_line_num>, and
110 C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
111 be used to indicate where the symbol should be regarded as having been defined.
112 Currently these values are only used if the symbol is a subroutine ('C<&>'
113 sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
114 hash is updated to record the values of C<filename>, C<first_line_num>, and
115 C<last_line_num> for the subroutine. If these are not passed, their values are
116 inferred (as much as possible) from C<caller> information.
118 This is especially useful for debuggers and profilers, which use C<%DB::sub> to
119 determine where the source code for a subroutine can be found. See
120 L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
121 information about C<%DB::sub>.
125 sub _valid_for_type {
127 my ($value, $type) = @_;
128 if ($type eq 'HASH' || $type eq 'ARRAY'
129 || $type eq 'IO' || $type eq 'CODE') {
130 return reftype($value) eq $type;
133 my $ref = reftype($value);
134 return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE';
138 sub add_package_symbol {
139 my ($self, $variable, $initial_value, %opts) = @_;
141 my ($name, $sigil, $type) = ref $variable eq 'HASH'
142 ? @{$variable}{qw[name sigil type]}
143 : $self->_deconstruct_variable_name($variable);
145 my $pkg = $self->name;
148 $self->_valid_for_type($initial_value, $type)
149 || confess "$initial_value is not of type $type";
151 # cheap fail-fast check for PERLDBf_SUBLINE and '&'
152 if ($^P and $^P & 0x10 && $sigil eq '&') {
153 my $filename = $opts{filename};
154 my $first_line_num = $opts{first_line_num};
156 (undef, $filename, $first_line_num) = caller
157 if not defined $filename;
159 my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
161 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
162 $DB::sub{$pkg . '::' . $name} = "$filename:$first_line_num-$last_line_num";
167 no warnings 'redefine', 'misc', 'prototype';
168 *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
171 =method remove_package_glob $name
173 Removes all package variables with the given name, regardless of sigil.
177 sub remove_package_glob {
178 my ($self, $name) = @_;
180 delete ${$self->name . '::'}{$name};
183 # ... these functions deal with stuff on the namespace level
185 =method has_package_symbol $variable
187 Returns whether or not the given package variable (including sigil) exists.
191 sub has_package_symbol {
192 my ($self, $variable) = @_;
194 my ($name, $sigil, $type) = ref $variable eq 'HASH'
195 ? @{$variable}{qw[name sigil type]}
196 : $self->_deconstruct_variable_name($variable);
198 my $namespace = $self->namespace;
200 return unless exists $namespace->{$name};
202 my $entry_ref = \$namespace->{$name};
203 if (reftype($entry_ref) eq 'GLOB') {
204 if ( $type eq 'SCALAR' ) {
205 return defined ${ *{$entry_ref}{SCALAR} };
208 return defined *{$entry_ref}{$type};
212 # a symbol table entry can be -1 (stub), string (stub with prototype),
213 # or reference (constant)
214 return $type eq 'CODE';
218 =method get_package_symbol $variable
220 Returns the value of the given package variable (including sigil).
224 sub get_package_symbol {
225 my ($self, $variable, %opts) = @_;
227 my ($name, $sigil, $type) = ref $variable eq 'HASH'
228 ? @{$variable}{qw[name sigil type]}
229 : $self->_deconstruct_variable_name($variable);
231 my $namespace = $self->namespace;
233 if (!exists $namespace->{$name}) {
235 if ($type eq 'ARRAY') {
236 $self->add_package_symbol(
238 # setting our own arrayref manually loses the magicalness
240 $name eq 'ISA' ? () : ([])
243 elsif ($type eq 'HASH') {
244 $self->add_package_symbol($variable, {});
246 elsif ($type eq 'SCALAR') {
247 $self->add_package_symbol($variable);
249 elsif ($type eq 'IO') {
250 $self->add_package_symbol($variable, Symbol::geniosym);
252 elsif ($type eq 'CODE') {
253 confess "Don't know how to vivify CODE variables";
256 confess "Unknown type $type in vivication";
260 if ($type eq 'CODE') {
261 # this effectively "de-vivifies" the code slot. if we don't do
262 # this, referencing the coderef at the end of this function
263 # will cause perl to auto-vivify a stub coderef in the slot,
264 # which isn't what we want
265 $self->add_package_symbol($variable);
270 my $entry_ref = \$namespace->{$name};
272 if (ref($entry_ref) eq 'GLOB') {
273 return *{$entry_ref}{$type};
276 if ($type eq 'CODE') {
278 return \&{ $self->name . '::' . $name };
286 =method get_or_add_package_symbol $variable
288 Like C<get_package_symbol>, except that it will return an empty hashref or
289 arrayref if the variable doesn't exist.
293 sub get_or_add_package_symbol {
295 $self->get_package_symbol(@_, vivify => 1);
298 =method remove_package_symbol $variable
300 Removes the package variable described by C<$variable> (which includes the
301 sigil); other variables with the same name but different sigils will be
306 sub remove_package_symbol {
307 my ($self, $variable) = @_;
309 my ($name, $sigil, $type) = ref $variable eq 'HASH'
310 ? @{$variable}{qw[name sigil type]}
311 : $self->_deconstruct_variable_name($variable);
314 # no doubt this is grossly inefficient and
315 # could be done much easier and faster in XS
317 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
318 { sigil => '$', type => 'SCALAR', name => $name },
319 { sigil => '@', type => 'ARRAY', name => $name },
320 { sigil => '%', type => 'HASH', name => $name },
321 { sigil => '&', type => 'CODE', name => $name },
322 { sigil => '', type => 'IO', name => $name },
325 my ($scalar, $array, $hash, $code, $io);
326 if ($type eq 'SCALAR') {
327 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
328 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
329 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
330 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
332 elsif ($type eq 'ARRAY') {
333 $scalar = $self->get_package_symbol($scalar_desc);
334 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
335 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
336 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
338 elsif ($type eq 'HASH') {
339 $scalar = $self->get_package_symbol($scalar_desc);
340 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
341 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
342 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
344 elsif ($type eq 'CODE') {
345 $scalar = $self->get_package_symbol($scalar_desc);
346 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
347 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
348 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
350 elsif ($type eq 'IO') {
351 $scalar = $self->get_package_symbol($scalar_desc);
352 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
353 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
354 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
357 confess "This should never ever ever happen";
360 $self->remove_package_glob($name);
362 $self->add_package_symbol($scalar_desc => $scalar);
363 $self->add_package_symbol($array_desc => $array) if defined $array;
364 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
365 $self->add_package_symbol($code_desc => $code) if defined $code;
366 $self->add_package_symbol($io_desc => $io) if defined $io;
369 =method list_all_package_symbols $type_filter
371 Returns a list of package variable names in the package, without sigils. If a
372 C<type_filter> is passed, it is used to select package variables of a given
373 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
378 sub list_all_package_symbols {
379 my ($self, $type_filter) = @_;
381 my $namespace = $self->namespace;
382 return keys %{$namespace} unless defined $type_filter;
385 # or we can filter based on
386 # type (SCALAR|ARRAY|HASH|CODE)
387 if ($type_filter eq 'CODE') {
389 (ref($namespace->{$_})
390 ? (ref($namespace->{$_}) eq 'SCALAR')
391 : (ref(\$namespace->{$_}) eq 'GLOB'
392 && defined(*{$namespace->{$_}}{CODE})));
393 } keys %{$namespace};
395 return grep { *{$namespace->{$_}}{$type_filter} } keys %{$namespace};
403 Please report any bugs through RT: email
404 C<bug-package-stash at rt.cpan.org>, or browse to
405 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
411 =item * L<Class::MOP::Package>
413 This module is a factoring out of code that used to live here
419 You can find this documentation for this module with the perldoc command.
421 perldoc Package::Stash
423 You can also look for information at:
427 =item * AnnoCPAN: Annotated CPAN documentation
429 L<http://annocpan.org/dist/Package-Stash>
433 L<http://cpanratings.perl.org/d/Package-Stash>
435 =item * RT: CPAN's request tracker
437 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
441 L<http://search.cpan.org/dist/Package-Stash>
447 Jesse Luehrs <doy at tozt dot net>
449 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the