in reply to Hash key manipulation question

Off the top of my head, a relatively inefficient method:

eval '$Hash' . map { qq({'$_'}) } @a . ' = 1';

Untested, of course ;-) A bit of description in order here: we're just creating the string you wanted. A bit more smarts to only put in the quotes when required, check if the hash you're trying to create already exists as a scalar rather than a hashref, etc., to prevent collisions, ... but if you know that collisions can't happen, then this should be fine.

UPDATE:After reading the other hash thread, I see someone of importance saying "don't use eval". And, as a general rule, I would agree. But I don't know if this is a one-off script (just do a quick conversion, and never use it again), or if the input is tightly controlled (e.g., can't be manipulated to circumvent perl security-isms, e.g., a string that had single-quotes in it: qq(blah' . system("rm -rf /") . 'blah)), or other mitigating circumstances. Sometimes quick and dirty is fine. A more robust method would use loops or even recursion to do this.

sub create_hash_depth { my $href = shift; my @a = @_; if (scalar @a > 1) { $href->{$a[0]} = {}; create_hash_depth($href->{$a[0]}, @a[1..$#a]); } else { $href->{$a[0]} = 1; } }

Or something like that

Replies are listed 'Best First'.
Re^2: Hash key manipulation question
by EchoAngel (Pilgrim) on Jan 11, 2005 at 19:11 UTC
    lol, i just read the other thread too. I have heard eval is dangerous to use. Thanks for all your help guys.