in reply to Missing something with regards to references
Instead of this, you need to keep another level of references. Now instead of trying to keep the values of $DATA{3}, $DATA{3}{h}, $DATA{3}{h}{i} (which are copied, so don't do the right thing if the hash key doesn't exist), we have to keep references to those slots of the hashes. This way the new hashes can be autovivified in the appropriate slot, and not into your temporary variable.
You also need to use $_[0] instead of shift if the first argument has a hash dereference that may be autovifified (since shift makes a copy, but $_[0] is an alias to the first arg, not a copy).
Yes, the autovivification makes this a very sticky situation. But if you can understand this, you are in very good shape with your understanding of references.sub put_element { my $current = \ $_[0]; shift; my $value = pop; $current = \ $$current->{ +shift } while @_; $$current = $value; } use Data::Dumper; my %DATA; put_element( $DATA{3}, 'h', 'i', "Worked" ); ## $DATA{3} autovifified + too put_element( $DATA{3}, 'b', 'y', 'e' ); ## $DATA{3} exists print Dumper \%DATA;
blokhead
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Missing something with regards to references
by scottb (Scribe) on Nov 01, 2004 at 23:27 UTC | |
by iblech (Friar) on Nov 03, 2004 at 10:47 UTC |