[tpm] Populating an unfixed number of hash elements
Madison Kelly
linux at alteeve.com
Fri May 9 08:43:55 PDT 2008
I am not sure that the subject makes a lot of sense, sorry. :)
In a few places I take a string that can have an arbitrary number of
elements in it that I use as hash keys. I split up this string and feed
in a passed value to a hash reference using the given hash elements.
So far, I've not found an effective way to do this, so I've resorted to
a frighteningly dumb solution "that works". However, it's not at all
flexible and frankly, I am ashamed of it. So please, TPM, help me regain
some dignity! :)
I need a way to /intelligently/ create a hash entry. I've tried
'eval'ing it into existence but that never seems to work for some reason...
Thanks!!
Madi
-=-=-=-=-=-=-=-
Here is an example of what I am trying to do:
my %hash=();
$string1="some::string::of::elements";
$string2="some::string";
$string3="some::string::of::other::elements";
$string4="another::set::of::keys";
$self->_to_hash(\%hash, $string1, "a value");
$self->_to_hash(\%hash, $string2, 12);
$self->_to_hash(\%hash, $string3, "a really long string that takes up
pages");
$self->_to_hash(\%hash, $string4, "something else again.");
sub _to_hash
{
my $self=shift;
my $hashref=shift;
my $keystring=shift;
my $value=shift;
my @key=split /::/, $hashref;
# Here is where it gets... undignified...
if (@key==5)
{
$$hashref{$key[0]}{$key[1]}{$key[2]}{$key[3]}{$key[4]}=$value;
}
elsif (@key==4)
{
$$hashref{$key[0]}{$key[1]}{$key[2]}{$key[3]}=$value;
}
elsif (@key==3)
{
$$hashref{$key[0]}{$key[1]}{$key[2]}=$value;
}
elsif (@key==2)
{
$$hashref{$key[0]}{$key[1]}=$value;
}
elsif (@key==1)
{
$$hashref{$key[0]}=$value;
}
else
{
croak "Unsupported number of kash keys.\n";
}
return();
}
More information about the toronto-pm
mailing list