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

Say I have three variables:
$name = 'hash1' $key = 'key1' $keyvalue = 'keyvalue1'

How would I write the equivalent of the line below using the variables   (i.e. something like: %($name)<br>=$key=>$keyvalue  )

%hash1 = key1=>'keyvalue1'
Thanks!

janitored by ybiC: Minor format cleanup, including balanced <code> tags around code snippets

Replies are listed 'Best First'.
Re: Beginners question: assigning a variable as the name of a hash
by ikegami (Patriarch) on Apr 22, 2005 at 19:41 UTC
    # Doesn't delete anything else in the %{$data{$name}} $data{$name}{$key} = $keyvalue; # Erases everything else in the %{$data{$name}}. %{$data{$name}} = ( $key => $keyvalue );

    It's bad to actually create variable dynamically. (You can see the reason for that here.) That's why I'm not creating a variable named %hash1. Rather, I created %data which hold %hash1 and any other hashes you wish to create dynamically.

Re: Beginners question: assigning a variable as the name of a hash
by dragonchild (Archbishop) on Apr 22, 2005 at 19:44 UTC
    You don't want to name your variables with strings contained in other variables. It sounds like you want a hash of hashes.
    my %datastore; $datastore{ $name }{ $key } = $keyvalue;

    Update: Fixed typo as per japhy's reply.

      You meant my %datastore;.
      _____________________________________________________
      Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
      How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Beginners question: assigning a variable as the name of a hash
by tlm (Prior) on Apr 22, 2005 at 19:48 UTC

    What you're trying to do involves symbolic references, which is probably not a good idea. Anyway, it's this:

    { no strict 'refs'; %$name = ( $key => $keyvalue ); }
    Note that I have switched off strict in a narrow enclosing scope; make sure you use it everywhere else.

    You should definitely read this series.

    the lowliest monk