http://qs321.pair.com?node_id=611674

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

Hi
Can I use a variable for value of a hash? for ex
$dw = "dw_urg"; %$dw_TG = qw( var $dw_VAR str $dw_STR mkt $dw_MKT ); foreach $key (keys %$dw_TG) { print "$$dw_TG{$key} -> $key\n"; }
This displays
$dw_MKT -> mkt $dw_STR -> str $dw_VAR -> var
but i need $dw to be replaced by its value. Please help

Replies are listed 'Best First'.
Re: Perl Hashes
by johngg (Canon) on Apr 24, 2007 at 10:29 UTC
    You can but there are two problems with your code. First, variables are not interpolated inside qw{ ... } so you are just getting the literal variable name so you need to set up the hash using key/value pairs in a list. Second, you need to disambiguate the $dw from the '_VAR' because $dw_VAR is also a valid variable name; you can do this by saying ${dw}_ARG. You are setting up a hash reference and it is probably less confusing if you use the { key => value, ... } anonymous hash constructor.

    It is a good idea to always do use strict; and use warnings at the top of your code. That would help you catch things like undeclared variables.

    use strict; use warnings; my $dw = q{dw_urg}; my $dw_TG = { var => qq{${dw}_VAR}, str => qq{${dw}_STR}, mkt => qq{${dw}_MKT}, };

    I hope this is useful.

    Cheers,

    JohnGG

Re: Perl Hashes
by dorward (Curate) on Apr 24, 2007 at 09:57 UTC

    > Can I use a variable for value of a hash?

    Yes

    > qw( var $dw_VAR

    qw doesn't interpolate

    %$dw_TG = ( var => $dw_VAR str => $dw_STR mkt => $dw_MKT );
Re: Perl Hashes
by betterworld (Curate) on Apr 24, 2007 at 09:55 UTC
    You may use references (see perlref) for this:
    my %hash = ( var => \$dw_VAR, str => \$dw_STR, ); print "str is ", ${$hash{str}}, "\n";