You could just not put the values in single quotes and have them interpolate e.g
my($foo, $bar, $baz) = qw/ one two three /; ## note the use of parens and *not* curly braces ## as they create an *anonymous hash reference* my %hash = ( key1 => $foo, key2 => $bar, key3 => $baz, ); print $hash{key1}; __output__ one
Although you probably want to interpolate values when you access them (i.e not when the hash is created), so just create a references to the respective variables e.g
my($foo, $bar, $baz) = qw/ one two three /; my %hash = ( key1 => \$foo, key2 => \$bar, key3 => \$baz, ); ## must dereference to get value print ${ $hash{key1} }, "\n"; $foo = 'something else'; print ${ $hash{key1} }, "\n"; __output__ one something else
Although that looks prime for a quick Tie::OneOff
use strict; use Tie::OneOff; my($foo, $bar, $baz) = qw/ one two three /; my %hash = ( key1 => \$foo, key2 => \$bar, key3 => \$baz, ); tie my %hash2, 'Tie::OneOff' => sub { ${ $hash{$_[0]} } }; print $hash2{key1}, "\n"; $foo = 'something else'; print $hash2{key1}, "\n"; __output__ one something else
Ain't perl neat?
HTH

_________
broquaint


In reply to Re: interpolate variable in a hash? by broquaint
in thread interpolate variable in a hash? by alienhuman

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.