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 if ( $type eq 'SCALAR' ) {
208 return defined ${ *{$entry_ref}{SCALAR} };
211 return defined *{$entry_ref}{$type};
215 # a symbol table entry can be -1 (stub), string (stub with prototype),
216 # or reference (constant)
217 return $type eq 'CODE';
221 =method get_package_symbol $variable
223 Returns the value of the given package variable (including sigil).
227 sub get_package_symbol {
228 my ($self, $variable, %opts) = @_;
230 my ($name, $sigil, $type) = ref $variable eq 'HASH'
231 ? @{$variable}{qw[name sigil type]}
232 : $self->_deconstruct_variable_name($variable);
234 my $namespace = $self->namespace;
236 if (!exists $namespace->{$name}) {
238 if ($type eq 'ARRAY') {
239 if (BROKEN_ISA_ASSIGNMENT) {
240 $self->add_package_symbol(
242 $name eq 'ISA' ? () : ([])
246 $self->add_package_symbol($variable, []);
249 elsif ($type eq 'HASH') {
250 $self->add_package_symbol($variable, {});
252 elsif ($type eq 'SCALAR') {
253 $self->add_package_symbol($variable);
255 elsif ($type eq 'IO') {
256 $self->add_package_symbol($variable, Symbol::geniosym);
258 elsif ($type eq 'CODE') {
259 confess "Don't know how to vivify CODE variables";
262 confess "Unknown type $type in vivication";
266 if ($type eq 'CODE') {
267 # this effectively "de-vivifies" the code slot. if we don't do
268 # this, referencing the coderef at the end of this function
269 # will cause perl to auto-vivify a stub coderef in the slot,
270 # which isn't what we want
271 $self->add_package_symbol($variable);
276 my $entry_ref = \$namespace->{$name};
278 if (ref($entry_ref) eq 'GLOB') {
279 return *{$entry_ref}{$type};
282 if ($type eq 'CODE') {
284 return \&{ $self->name . '::' . $name };
292 =method get_or_add_package_symbol $variable
294 Like C<get_package_symbol>, except that it will return an empty hashref or
295 arrayref if the variable doesn't exist.
299 sub get_or_add_package_symbol {
301 $self->get_package_symbol(@_, vivify => 1);
304 =method remove_package_symbol $variable
306 Removes the package variable described by C<$variable> (which includes the
307 sigil); other variables with the same name but different sigils will be
312 sub remove_package_symbol {
313 my ($self, $variable) = @_;
315 my ($name, $sigil, $type) = ref $variable eq 'HASH'
316 ? @{$variable}{qw[name sigil type]}
317 : $self->_deconstruct_variable_name($variable);
320 # no doubt this is grossly inefficient and
321 # could be done much easier and faster in XS
323 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
324 { sigil => '$', type => 'SCALAR', name => $name },
325 { sigil => '@', type => 'ARRAY', name => $name },
326 { sigil => '%', type => 'HASH', name => $name },
327 { sigil => '&', type => 'CODE', name => $name },
328 { sigil => '', type => 'IO', name => $name },
331 my ($scalar, $array, $hash, $code, $io);
332 if ($type eq 'SCALAR') {
333 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_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 'ARRAY') {
339 $scalar = $self->get_package_symbol($scalar_desc);
340 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_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 'HASH') {
345 $scalar = $self->get_package_symbol($scalar_desc);
346 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
347 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
348 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
350 elsif ($type eq 'CODE') {
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 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
356 elsif ($type eq 'IO') {
357 $scalar = $self->get_package_symbol($scalar_desc);
358 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
359 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
360 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
363 confess "This should never ever ever happen";
366 $self->remove_package_glob($name);
368 $self->add_package_symbol($scalar_desc => $scalar);
369 $self->add_package_symbol($array_desc => $array) if defined $array;
370 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
371 $self->add_package_symbol($code_desc => $code) if defined $code;
372 $self->add_package_symbol($io_desc => $io) if defined $io;
375 =method list_all_package_symbols $type_filter
377 Returns a list of package variable names in the package, without sigils. If a
378 C<type_filter> is passed, it is used to select package variables of a given
379 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
384 sub list_all_package_symbols {
385 my ($self, $type_filter) = @_;
387 my $namespace = $self->namespace;
388 return keys %{$namespace} unless defined $type_filter;
391 # or we can filter based on
392 # type (SCALAR|ARRAY|HASH|CODE)
393 if ($type_filter eq 'CODE') {
395 (ref($namespace->{$_})
396 ? (ref($namespace->{$_}) eq 'SCALAR')
397 : (ref(\$namespace->{$_}) eq 'GLOB'
398 && defined(*{$namespace->{$_}}{CODE})));
399 } keys %{$namespace};
401 return grep { *{$namespace->{$_}}{$type_filter} } keys %{$namespace};
409 Please report any bugs through RT: email
410 C<bug-package-stash at rt.cpan.org>, or browse to
411 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
417 =item * L<Class::MOP::Package>
419 This module is a factoring out of code that used to live here
425 You can find this documentation for this module with the perldoc command.
427 perldoc Package::Stash
429 You can also look for information at:
433 =item * AnnoCPAN: Annotated CPAN documentation
435 L<http://annocpan.org/dist/Package-Stash>
439 L<http://cpanratings.perl.org/d/Package-Stash>
441 =item * RT: CPAN's request tracker
443 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
447 L<http://search.cpan.org/dist/Package-Stash>
453 Jesse Luehrs <doy at tozt dot net>
455 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the