1 package Package::Stash;
4 # ABSTRACT: routines for manipulating stashes
7 use Scalar::Util qw(reftype);
11 my $stash = Package::Stash->new('Foo');
12 $stash->add_package_symbol('%foo', {bar => 1});
14 $stash->has_package_symbol('$foo') # false
15 my $namespace = $stash->namespace;
16 *{ $namespace->{foo} }{HASH} # {bar => 1}
20 Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
21 incredibly messy, and easy to get wrong. This module hides all of that behind a
24 NOTE: Most methods in this class require a variable specification that includes
25 a sigil. If this sigil is absent, it is assumed to represent the IO slot.
27 =method new $package_name
29 Creates a new C<Package::Stash> object, for the package given as the only
40 # supposedly this caused a bug in earlier perls, but I can't reproduce
41 # it, so re-enabling the caching
42 $namespace = \%{$package . '::'};
45 'package' => $package,
46 'namespace' => $namespace,
52 Returns the name of the package that this object represents.
57 return $_[0]->{package};
62 Returns the raw stash itself.
67 return $_[0]->{namespace};
79 sub _deconstruct_variable_name {
80 my ($self, $variable) = @_;
82 (defined $variable && length $variable)
83 || confess "You must pass a variable name";
85 my $sigil = substr($variable, 0, 1, '');
87 if (exists $SIGIL_MAP{$sigil}) {
88 return ($variable, $sigil, $SIGIL_MAP{$sigil});
91 return ("${sigil}${variable}", '', $SIGIL_MAP{''});
96 =method add_package_symbol $variable $value %opts
98 Adds a new package symbol, for the symbol given as C<$variable>, and optionally
99 gives it an initial value of C<$value>. C<$variable> should be the name of
100 variable including the sigil, so
102 Package::Stash->new('Foo')->add_package_symbol('%foo')
104 will create C<%Foo::foo>.
106 Valid options (all optional) are C<filename>, C<first_line_num>, and
109 C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
110 be used to indicate where the symbol should be regarded as having been defined.
111 Currently these values are only used if the symbol is a subroutine ('C<&>'
112 sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
113 hash is updated to record the values of C<filename>, C<first_line_num>, and
114 C<last_line_num> for the subroutine. If these are not passed, their values are
115 inferred (as much as possible) from C<caller> information.
117 This is especially useful for debuggers and profilers, which use C<%DB::sub> to
118 determine where the source code for a subroutine can be found. See
119 L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
120 information about C<%DB::sub>.
124 sub _valid_for_type {
126 my ($value, $type) = @_;
127 if ($type eq 'HASH' || $type eq 'ARRAY'
128 || $type eq 'IO' || $type eq 'CODE') {
129 return reftype($value) eq $type;
132 my $ref = reftype($value);
133 return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE';
137 sub add_package_symbol {
138 my ($self, $variable, $initial_value, %opts) = @_;
140 my ($name, $sigil, $type) = ref $variable eq 'HASH'
141 ? @{$variable}{qw[name sigil type]}
142 : $self->_deconstruct_variable_name($variable);
144 my $pkg = $self->name;
147 $self->_valid_for_type($initial_value, $type)
148 || confess "$initial_value is not of type $type";
150 # cheap fail-fast check for PERLDBf_SUBLINE and '&'
151 if ($^P and $^P & 0x10 && $sigil eq '&') {
152 my $filename = $opts{filename};
153 my $first_line_num = $opts{first_line_num};
155 (undef, $filename, $first_line_num) = caller
156 if not defined $filename;
158 my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
160 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
161 $DB::sub{$pkg . '::' . $name} = "$filename:$first_line_num-$last_line_num";
166 no warnings 'redefine', 'misc', 'prototype';
167 *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
170 =method remove_package_glob $name
172 Removes all package variables with the given name, regardless of sigil.
176 sub remove_package_glob {
177 my ($self, $name) = @_;
179 delete ${$self->name . '::'}{$name};
182 # ... these functions deal with stuff on the namespace level
184 =method has_package_symbol $variable
186 Returns whether or not the given package variable (including sigil) exists.
190 sub has_package_symbol {
191 my ($self, $variable) = @_;
193 my ($name, $sigil, $type) = ref $variable eq 'HASH'
194 ? @{$variable}{qw[name sigil type]}
195 : $self->_deconstruct_variable_name($variable);
197 my $namespace = $self->namespace;
199 return unless exists $namespace->{$name};
201 my $entry_ref = \$namespace->{$name};
202 if (reftype($entry_ref) eq 'GLOB') {
203 if ( $type eq 'SCALAR' ) {
204 return defined ${ *{$entry_ref}{SCALAR} };
207 return defined *{$entry_ref}{$type};
211 # a symbol table entry can be -1 (stub), string (stub with prototype),
212 # or reference (constant)
213 return $type eq 'CODE';
217 =method get_package_symbol $variable
219 Returns the value of the given package variable (including sigil).
223 sub get_package_symbol {
224 my ($self, $variable, %opts) = @_;
226 my ($name, $sigil, $type) = ref $variable eq 'HASH'
227 ? @{$variable}{qw[name sigil type]}
228 : $self->_deconstruct_variable_name($variable);
230 my $namespace = $self->namespace;
232 if (!exists $namespace->{$name}) {
233 # assigning to the result of this function like
234 # @{$stash->get_package_symbol('@ISA')} = @new_ISA
235 # makes the result not visible until the variable is explicitly
236 # accessed... in the case of @ISA, this might never happen
237 # for instance, assigning like that and then calling $obj->isa
238 # will fail. see t/005-isa.t
239 if ($opts{vivify} && $type eq 'ARRAY' && $name ne 'ISA') {
240 $self->add_package_symbol($variable, []);
242 elsif ($opts{vivify} && $type eq 'HASH') {
243 $self->add_package_symbol($variable, {});
247 $self->add_package_symbol($variable)
251 my $entry_ref = \$namespace->{$name};
253 if (ref($entry_ref) eq 'GLOB') {
254 return *{$entry_ref}{$type};
257 if ($type eq 'CODE') {
259 return \&{ $self->name . '::' . $name };
267 =method get_or_add_package_symbol $variable
269 Like C<get_package_symbol>, except that it will return an empty hashref or
270 arrayref if the variable doesn't exist.
274 sub get_or_add_package_symbol {
276 $self->get_package_symbol(@_, vivify => 1);
279 =method remove_package_symbol $variable
281 Removes the package variable described by C<$variable> (which includes the
282 sigil); other variables with the same name but different sigils will be
287 sub remove_package_symbol {
288 my ($self, $variable) = @_;
290 my ($name, $sigil, $type) = ref $variable eq 'HASH'
291 ? @{$variable}{qw[name sigil type]}
292 : $self->_deconstruct_variable_name($variable);
295 # no doubt this is grossly inefficient and
296 # could be done much easier and faster in XS
298 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
299 { sigil => '$', type => 'SCALAR', name => $name },
300 { sigil => '@', type => 'ARRAY', name => $name },
301 { sigil => '%', type => 'HASH', name => $name },
302 { sigil => '&', type => 'CODE', name => $name },
303 { sigil => '', type => 'IO', name => $name },
306 my ($scalar, $array, $hash, $code, $io);
307 if ($type eq 'SCALAR') {
308 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
309 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
310 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
311 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
313 elsif ($type eq 'ARRAY') {
314 $scalar = $self->get_package_symbol($scalar_desc);
315 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
316 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
317 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
319 elsif ($type eq 'HASH') {
320 $scalar = $self->get_package_symbol($scalar_desc);
321 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
322 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
323 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
325 elsif ($type eq 'CODE') {
326 $scalar = $self->get_package_symbol($scalar_desc);
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 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
331 elsif ($type eq 'IO') {
332 $scalar = $self->get_package_symbol($scalar_desc);
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);
338 confess "This should never ever ever happen";
341 $self->remove_package_glob($name);
343 $self->add_package_symbol($scalar_desc => $scalar);
344 $self->add_package_symbol($array_desc => $array) if defined $array;
345 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
346 $self->add_package_symbol($code_desc => $code) if defined $code;
347 $self->add_package_symbol($io_desc => $io) if defined $io;
350 =method list_all_package_symbols $type_filter
352 Returns a list of package variable names in the package, without sigils. If a
353 C<type_filter> is passed, it is used to select package variables of a given
354 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
359 sub list_all_package_symbols {
360 my ($self, $type_filter) = @_;
362 my $namespace = $self->namespace;
363 return keys %{$namespace} unless defined $type_filter;
366 # or we can filter based on
367 # type (SCALAR|ARRAY|HASH|CODE)
368 if ($type_filter eq 'CODE') {
370 (ref($namespace->{$_})
371 ? (ref($namespace->{$_}) eq 'SCALAR')
372 : (ref(\$namespace->{$_}) eq 'GLOB'
373 && defined(*{$namespace->{$_}}{CODE})));
374 } keys %{$namespace};
376 return grep { *{$namespace->{$_}}{$type_filter} } keys %{$namespace};
384 Please report any bugs through RT: email
385 C<bug-package-stash at rt.cpan.org>, or browse to
386 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
392 =item * L<Class::MOP::Package>
394 This module is a factoring out of code that used to live here
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