=cut
sub get_package_symbol {
- my ($self, $variable) = @_;
+ my ($self, $variable, %opts) = @_;
my ($name, $sigil, $type) = ref $variable eq 'HASH'
? @{$variable}{qw[name sigil type]}
my $namespace = $self->namespace;
if (!exists $namespace->{$name}) {
- $self->add_package_symbol($variable)
+ # assigning to the result of this function like
+ # @{$stash->get_package_symbol('@ISA')} = @new_ISA
+ # makes the result not visible until the variable is explicitly
+ # accessed... in the case of @ISA, this might never happen
+ # for instance, assigning like that and then calling $obj->isa
+ # will fail. see t/005-isa.t
+ if ($opts{vivify} && $type eq 'ARRAY' && $name ne 'ISA') {
+ $self->add_package_symbol($variable, []);
+ }
+ elsif ($opts{vivify} && $type eq 'HASH') {
+ $self->add_package_symbol($variable, {});
+ }
+ else {
+ # FIXME
+ $self->add_package_symbol($variable)
+ }
}
my $entry_ref = \$namespace->{$name};
}
}
+=head2 get_or_add_package_symbol $variable
+
+Like C<get_package_symbol>, except that it will return an empty hashref or
+arrayref if the variable doesn't exist.
+
+=cut
+
+sub get_or_add_package_symbol {
+ my $self = shift;
+ $self->get_package_symbol(@_, vivify => 1);
+}
+
=head2 remove_package_symbol $variable
Removes the package variable described by C<$variable> (which includes the
}
}
+{
+ my $stash = Package::Stash->new('Baz');
+ my $val = $stash->get_or_add_package_symbol('%foo');
+ is(ref($val), 'HASH', "got something");
+ $val->{bar} = 1;
+ is_deeply($stash->get_or_add_package_symbol('%foo'), {bar => 1},
+ "got the right variable");
+}
+
+{
+ my $stash = Package::Stash->new('Quux');
+ my $val = $stash->get_or_add_package_symbol('@foo');
+ is(ref($val), 'ARRAY', "got something");
+ push @$val, 1;
+ is_deeply($stash->get_or_add_package_symbol('@foo'), [1],
+ "got the right variable");
+}
+
done_testing;