1 package Package::Stash;
4 # ABSTRACT: routines for manipulating stashes
7 use Scalar::Util qw(reftype);
9 # before 5.12, assigning to the ISA glob would make it lose its magical ->isa
11 use constant BROKEN_ISA_ASSIGNMENT => ($] < 5.012);
15 my $stash = Package::Stash->new('Foo');
16 $stash->add_package_symbol('%foo', {bar => 1});
18 $stash->has_package_symbol('$foo') # false
19 my $namespace = $stash->namespace;
20 *{ $namespace->{foo} }{HASH} # {bar => 1}
24 Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
25 incredibly messy, and easy to get wrong. This module hides all of that behind a
28 NOTE: Most methods in this class require a variable specification that includes
29 a sigil. If this sigil is absent, it is assumed to represent the IO slot.
31 =method new $package_name
33 Creates a new C<Package::Stash> object, for the package given as the only
44 # supposedly this caused a bug in earlier perls, but I can't reproduce
45 # it, so re-enabling the caching
46 $namespace = \%{$package . '::'};
49 'package' => $package,
50 'namespace' => $namespace,
56 Returns the name of the package that this object represents.
61 return $_[0]->{package};
66 Returns the raw stash itself.
71 return $_[0]->{namespace};
83 sub _deconstruct_variable_name {
84 my ($self, $variable) = @_;
86 (defined $variable && length $variable)
87 || confess "You must pass a variable name";
89 my $sigil = substr($variable, 0, 1, '');
91 if (exists $SIGIL_MAP{$sigil}) {
92 return ($variable, $sigil, $SIGIL_MAP{$sigil});
95 return ("${sigil}${variable}", '', $SIGIL_MAP{''});
100 =method add_package_symbol $variable $value %opts
102 Adds a new package symbol, for the symbol given as C<$variable>, and optionally
103 gives it an initial value of C<$value>. C<$variable> should be the name of
104 variable including the sigil, so
106 Package::Stash->new('Foo')->add_package_symbol('%foo')
108 will create C<%Foo::foo>.
110 Valid options (all optional) are C<filename>, C<first_line_num>, and
113 C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
114 be used to indicate where the symbol should be regarded as having been defined.
115 Currently these values are only used if the symbol is a subroutine ('C<&>'
116 sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
117 hash is updated to record the values of C<filename>, C<first_line_num>, and
118 C<last_line_num> for the subroutine. If these are not passed, their values are
119 inferred (as much as possible) from C<caller> information.
121 This is especially useful for debuggers and profilers, which use C<%DB::sub> to
122 determine where the source code for a subroutine can be found. See
123 L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
124 information about C<%DB::sub>.
128 sub _valid_for_type {
130 my ($value, $type) = @_;
131 if ($type eq 'HASH' || $type eq 'ARRAY'
132 || $type eq 'IO' || $type eq 'CODE') {
133 return reftype($value) eq $type;
136 my $ref = reftype($value);
137 return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE';
141 sub add_package_symbol {
142 my ($self, $variable, $initial_value, %opts) = @_;
144 my ($name, $sigil, $type) = ref $variable eq 'HASH'
145 ? @{$variable}{qw[name sigil type]}
146 : $self->_deconstruct_variable_name($variable);
148 my $pkg = $self->name;
151 $self->_valid_for_type($initial_value, $type)
152 || confess "$initial_value is not of type $type";
154 # cheap fail-fast check for PERLDBf_SUBLINE and '&'
155 if ($^P and $^P & 0x10 && $sigil eq '&') {
156 my $filename = $opts{filename};
157 my $first_line_num = $opts{first_line_num};
159 (undef, $filename, $first_line_num) = caller
160 if not defined $filename;
162 my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
164 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
165 $DB::sub{$pkg . '::' . $name} = "$filename:$first_line_num-$last_line_num";
170 no warnings 'redefine', 'misc', 'prototype';
171 *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
174 =method remove_package_glob $name
176 Removes all package variables with the given name, regardless of sigil.
180 sub remove_package_glob {
181 my ($self, $name) = @_;
183 delete ${$self->name . '::'}{$name};
186 # ... these functions deal with stuff on the namespace level
188 =method has_package_symbol $variable
190 Returns whether or not the given package variable (including sigil) exists.
194 sub has_package_symbol {
195 my ($self, $variable) = @_;
197 my ($name, $sigil, $type) = ref $variable eq 'HASH'
198 ? @{$variable}{qw[name sigil type]}
199 : $self->_deconstruct_variable_name($variable);
201 my $namespace = $self->namespace;
203 return unless exists $namespace->{$name};
205 my $entry_ref = \$namespace->{$name};
206 if (reftype($entry_ref) eq 'GLOB') {
207 # XXX: assigning to any typeglob slot also initializes the SCALAR slot,
208 # and saying that an undef scalar variable doesn't exist is probably
209 # vaguely less surprising than a scalar variable popping into existence
210 # without anyone defining it
211 if ($type eq 'SCALAR') {
212 return defined ${ *{$entry_ref}{$type} };
215 return defined *{$entry_ref}{$type};
219 # a symbol table entry can be -1 (stub), string (stub with prototype),
220 # or reference (constant)
221 return $type eq 'CODE';
225 =method get_package_symbol $variable
227 Returns the value of the given package variable (including sigil).
231 sub get_package_symbol {
232 my ($self, $variable, %opts) = @_;
234 my ($name, $sigil, $type) = ref $variable eq 'HASH'
235 ? @{$variable}{qw[name sigil type]}
236 : $self->_deconstruct_variable_name($variable);
238 my $namespace = $self->namespace;
240 if (!exists $namespace->{$name}) {
242 if ($type eq 'ARRAY') {
243 if (BROKEN_ISA_ASSIGNMENT) {
244 $self->add_package_symbol(
246 $name eq 'ISA' ? () : ([])
250 $self->add_package_symbol($variable, []);
253 elsif ($type eq 'HASH') {
254 $self->add_package_symbol($variable, {});
256 elsif ($type eq 'SCALAR') {
257 $self->add_package_symbol($variable);
259 elsif ($type eq 'IO') {
260 $self->add_package_symbol($variable, Symbol::geniosym);
262 elsif ($type eq 'CODE') {
263 confess "Don't know how to vivify CODE variables";
266 confess "Unknown type $type in vivication";
270 if ($type eq 'CODE') {
271 # this effectively "de-vivifies" the code slot. if we don't do
272 # this, referencing the coderef at the end of this function
273 # will cause perl to auto-vivify a stub coderef in the slot,
274 # which isn't what we want
275 $self->add_package_symbol($variable);
280 my $entry_ref = \$namespace->{$name};
282 if (ref($entry_ref) eq 'GLOB') {
283 return *{$entry_ref}{$type};
286 if ($type eq 'CODE') {
288 return \&{ $self->name . '::' . $name };
296 =method get_or_add_package_symbol $variable
298 Like C<get_package_symbol>, except that it will return an empty hashref or
299 arrayref if the variable doesn't exist.
303 sub get_or_add_package_symbol {
305 $self->get_package_symbol(@_, vivify => 1);
308 =method remove_package_symbol $variable
310 Removes the package variable described by C<$variable> (which includes the
311 sigil); other variables with the same name but different sigils will be
316 sub remove_package_symbol {
317 my ($self, $variable) = @_;
319 my ($name, $sigil, $type) = ref $variable eq 'HASH'
320 ? @{$variable}{qw[name sigil type]}
321 : $self->_deconstruct_variable_name($variable);
324 # no doubt this is grossly inefficient and
325 # could be done much easier and faster in XS
327 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
328 { sigil => '$', type => 'SCALAR', name => $name },
329 { sigil => '@', type => 'ARRAY', name => $name },
330 { sigil => '%', type => 'HASH', name => $name },
331 { sigil => '&', type => 'CODE', name => $name },
332 { sigil => '', type => 'IO', name => $name },
335 my ($scalar, $array, $hash, $code, $io);
336 if ($type eq 'SCALAR') {
337 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
338 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
339 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
340 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
342 elsif ($type eq 'ARRAY') {
343 $scalar = $self->get_package_symbol($scalar_desc);
344 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
345 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
346 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
348 elsif ($type eq 'HASH') {
349 $scalar = $self->get_package_symbol($scalar_desc);
350 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
351 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
352 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
354 elsif ($type eq 'CODE') {
355 $scalar = $self->get_package_symbol($scalar_desc);
356 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
357 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
358 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
360 elsif ($type eq 'IO') {
361 $scalar = $self->get_package_symbol($scalar_desc);
362 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
363 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
364 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
367 confess "This should never ever ever happen";
370 $self->remove_package_glob($name);
372 $self->add_package_symbol($scalar_desc => $scalar);
373 $self->add_package_symbol($array_desc => $array) if defined $array;
374 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
375 $self->add_package_symbol($code_desc => $code) if defined $code;
376 $self->add_package_symbol($io_desc => $io) if defined $io;
379 =method list_all_package_symbols $type_filter
381 Returns a list of package variable names in the package, without sigils. If a
382 C<type_filter> is passed, it is used to select package variables of a given
383 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
384 etc). Note that if the package contained any C<BEGIN> blocks, perl will leave
385 an empty typeglob in the C<BEGIN> slot, so this will show up if no filter is
386 used (and similarly for C<INIT>, C<END>, etc).
390 sub list_all_package_symbols {
391 my ($self, $type_filter) = @_;
393 my $namespace = $self->namespace;
394 return keys %{$namespace} unless defined $type_filter;
397 # or we can filter based on
398 # type (SCALAR|ARRAY|HASH|CODE)
399 if ($type_filter eq 'CODE') {
401 # any non-typeglob in the symbol table is a constant or stub
402 ref(\$namespace->{$_}) ne 'GLOB'
403 # regular subs are stored in the CODE slot of the typeglob
404 || defined(*{$namespace->{$_}}{CODE})
405 } keys %{$namespace};
407 elsif ($type_filter eq 'SCALAR') {
409 ref(\$namespace->{$_}) eq 'GLOB'
410 && defined(${*{$namespace->{$_}}{'SCALAR'}})
411 } keys %{$namespace};
415 ref(\$namespace->{$_}) eq 'GLOB'
416 && defined(*{$namespace->{$_}}{$type_filter})
417 } keys %{$namespace};
425 Please report any bugs through RT: email
426 C<bug-package-stash at rt.cpan.org>, or browse to
427 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
433 =item * L<Class::MOP::Package>
435 This module is a factoring out of code that used to live here
441 You can find this documentation for this module with the perldoc command.
443 perldoc Package::Stash
445 You can also look for information at:
449 =item * AnnoCPAN: Annotated CPAN documentation
451 L<http://annocpan.org/dist/Package-Stash>
455 L<http://cpanratings.perl.org/d/Package-Stash>
457 =item * RT: CPAN's request tracker
459 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
463 L<http://search.cpan.org/dist/Package-Stash>
469 Jesse Luehrs <doy at tozt dot net>
471 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the