in reply to Missing something with regards to references
Lets start with the function usage model: You suggest
For clarity, lets do the whole hash. You can create a reference to the top level (root) hash using the backslash operator:put_element( $DATA{3}, 'h', 'i', 'worked' );
All those quotes get tiresome after a while, so lets get rid of them:put_element( \%DATA, 3, 'h', 'i', 'worked' );
Perl flattens arg-lists, so that is identical to the previous version.put_element( \%DATA, qw(3 h i worked) );
So now the implementation (I'll omit the error-checks):
Hopefully the comments are sufficient to explain my thinking.sub put_element { my ($hashref, @path) = @_; # The leaf node and its value are special my $value = pop @path; my $leaf = pop @path; # walk the tree, create non-existing nodes for my $node (@path) { $hashref = $hashref->{$node} ||= {}; } # Finally, set the value at the leaf $hashref->{$leaf} = $value; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Missing something with regards to references
by scottb (Scribe) on Nov 02, 2004 at 00:03 UTC | |
by dpuu (Chaplain) on Nov 02, 2004 at 00:39 UTC |