does not leave around refs to empty hashes (it leaves undef's instead).
What does that mean? In fact, vivification is required here.
use strict;
use warnings;
use Data::Dumper qw( Dumper );
sub samtregar {
my $p = shift;
my $val = pop;
for my $item (@_) {
$p->{$item} ||= {};
$p = $p->{$item};
}
$p->{_val} = $val;
}
sub repellent {
my $p = \shift;
my $val = pop;
$p = \$$p->{$_} for @_;
$$p->{_val} = $val;
}
{
samtregar(my $samtregar={}, qw( a b c d ), 'foo');
repellent(my $repellent, qw( a b c d ), 'foo');
{
local $Data::Dumper::Useqq = 1;
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Indent = 0;
print("samtregar: ", Dumper($samtregar), "\n");
print("repellent: ", Dumper($repellent), "\n");
}
}
samtregar: {"a" => {"b" => {"c" => {"d" => {"_val" => "foo"}}}}}
repellent: {"a" => {"b" => {"c" => {"d" => {"_val" => "foo"}}}}}
And for a getter, what you said is backwards. Yours is the one that vivifies.
use strict;
use warnings;
use Data::Dumper qw( Dumper );
sub samtregar_fetcher {
my $p = shift;
for my $item (@_) {
last if !$p->{$item};
$p = $p->{$item};
}
return $p->{_val}
}
sub repellent_fetcher {
my $p = \shift;
my $val = pop;
$p = \$$p->{$_} for @_;
return $$p->{_val};
}
{
samtregar_fetcher(my $samtregar={}, qw( a b c d ));
repellent_fetcher(my $repellent, qw( a b c d ));
{
local $Data::Dumper::Useqq = 1;
local $Data::Dumper::Terse = 1;
local $Data::Dumper::Indent = 0;
print("samtregar: ", Dumper($samtregar), "\n");
print("repellent: ", Dumper($repellent), "\n");
}
}
samtregar: {}
repellent: {"a" => {"b" => {"c" => {}}}}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.