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.gmy($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 that looks prime for a quick Tie::OneOffmy($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
Ain't perl neat?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
_________
broquaint
In reply to Re: interpolate variable in a hash?
by broquaint
in thread interpolate variable in a hash?
by alienhuman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |