edwardt_tril has asked for the wisdom of the Perl Monks concerning the following question:

Hi I am trying to upadte values of a subkey of a "hash of hash"
. I don't think code: $self->{$keyname}{$keysubname}=
$keyvalue; is the best way. What I try to acomplish is
that.. I have a bunch of get and set functions that try
to update the subkey values (husband, pal). but I want
these functions just to call a generic function
(updateSubkey) such that you supplying the names of the
keys and the key values then you will do the update.
this way, I centrazlise the main logic and any change is
requried to that one function and not requrie me to do
the same change to all the others.. e.g.
updatesubKey(flintstone,husband,"joe"); How can I do that? thanks
use Data::Dumper; my %HoH = ( flintstones => { husband => "fred", pal => "barney", }, jetsons => { husband => "george", wife => "jane", "his boy" => "elroy", # Key quotes needed. }, simpsons => { husband => "homer", wife => "marge", kid => "bart", }, ); sub new { my $class = shift; my %self = %HoH; bless \%self, $class; } sub updatename{ my ($self, $keyname, $keysubname,$keyvalue)=@_; $self->{$keyname}{$keysubname}= {$keyvalue}; } print Dumper(%HoH); updatename("flintstones","husband","joe"); print Dumper(%HoH);

Replies are listed 'Best First'.
Re: updating hash of hash
by ikegami (Patriarch) on Mar 21, 2006 at 20:12 UTC
    • You implemented updatename as a method, but you're not calling it as a method. I'm not sure why this is a method at all.
    • You used curly braces around your arguments where you should have used parens.
    • You have curly braces around $keyvalue when you shouldn't.
    my %HoH = ...; sub updatename { my ($keyname, $keysubname, $keyvalue) = @_; $HoH{$keyname}{$keysubname} = $keyvalue; } updatename("flintstones", "husband", "joe"); # or # updatename(flintstones => husband => "joe");
Re: updating hash of hash
by kwaping (Priest) on Mar 21, 2006 at 20:56 UTC
    I don't think code: $self->{$keyname}{$keysubname}= $keyvalue; is the best way.

    What's wrong with that method? Seems very straightforward to me. The only way I would consider using a function to be superior is if you were validating the keys or data in some way (which isn't in your posted code).

    ---
    It's all fine and dandy until someone has to look at the code.