in reply to Mandatory Symbolic References?

Of course, you want to go the other way, if you merely want to convert a set of variables into a hash, there is no need to use globs or symbolic references. Just use eval, but this too can get you into trouble if you over use it. And be sure to put the variable sigal '$' into single quotes, e.g.

my %hash; $hash{alpha}{state} = eval('$A::alpha_state'); print '$hash{alpha}{state}=', $hash{alpha}{state}, "\n";

Or more generally,

our $alpha_state = 'STATE'; our $beta_state = 'state'; our $alpha_country = 'COUNTRY'; our $beta_country = 'country'; my %hash; # convert yucky legacy variables into nice hashes for my $k1 qw(alpha beta) { for my $k2 qw(country state) { $hash{$k1}{$k2} = eval '$'.$k1.'_'.$k2; } } # print out the hash for my $k1 (keys %hash) { for my $k2 (keys %{$hash{$k1}}) { print "$k1,$k2=",$hash{$k1}{$k2},"\n"; } } #outputs alpha,country=COUNTRY alpha,state=STATE beta,country=country beta,state=state

Update: reworded intro to take into account alternate reading of OP's question (see replies below).

Replies are listed 'Best First'.
Re^2: Mandatory Symbolic References?
by Anonyrnous Monk (Hermit) on Jan 18, 2011 at 21:35 UTC

    As I understand it, the OP wants the hash entry to be an alias to the legacy $alpha_state variable, so that both see the same value ("I want the hash value $hash{alpha}{state} to always equal $alpha_state."). Or put differently, if either one of them is being changed, the other one automatically holds the changed value as well.

    eval only assigns the value the variable holds at the time of the eval. If it changes afterwards, the hash entry will not be updated; nor will changing the hash entry update $alpha_state.

      If that is what he means, I agree with your analysis - my solution does not update nor was it intended to.

      I took my interpretation from the example he gave where it seemed to me that what he wanted was an easy way to assign a set of regularly named variables into hash keys based on the variable naming conventions. I assumed that the "$alpha_state" value was essentially a constant because that is how the OP presented it - the inherited code assigned it a value. This is a pattern I've seen before - read in data from a CGI stream, populate some variables and never change them, then read the variables later on to either re-present the data or use it as input to some calculation. I just recently analyzed such code in a post Re: This runs WAY too slow.

      Even though an alias would be more powerful than my solution (being read/write), I don't like creating such alaises unless it is really, really necessary. It makes the program that much harder to maintain and adds to the documentation burden.

      But only the OP actually knows what he wants, so maybe he/she will tell us?