[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...



Here is an example of what I am trying to do:

my %hash=();


$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 
$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)
	elsif (@key==4)
	elsif (@key==3)
	elsif (@key==2)
	elsif (@key==1)
	  croak "Unsupported number of kash keys.\n";


More information about the toronto-pm mailing list