add get_or_add_package_symbol, for the vivify behavior
[gitmo/Package-Stash.git] / lib / Package / Stash.pm
index 6f0910c..6396ed5 100644 (file)
@@ -226,7 +226,7 @@ Returns the value of the given package variable (including sigil).
 =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]}
@@ -241,10 +241,10 @@ sub get_package_symbol {
         # 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 ($type eq 'ARRAY' && $name ne 'ISA') {
+        if ($opts{vivify} && $type eq 'ARRAY' && $name ne 'ISA') {
             $self->add_package_symbol($variable, []);
         }
-        elsif ($type eq 'HASH') {
+        elsif ($opts{vivify} && $type eq 'HASH') {
             $self->add_package_symbol($variable, {});
         }
         else {
@@ -269,6 +269,18 @@ sub get_package_symbol {
     }
 }
 
+=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