How would I create a hash like the follow:
my %hash = (key1=>"Something", key2=>$hash{key1} . "Else");
Can this not be done while when I declare the hash? So far, the only thing I came up with was:
my %hash = (key1=>"Something");
$hash{key2} = $hash{key1} . "Else";
Why not use an intermediate variable?
Update
kemp asked why we need an intermediate variable. I can interpret this question it two ways, I’ll endeavor to answer both interpretations.
Why can’t you do
my %hash = ( k1 => 'foo', k2 => $hash{k1}.'bar' );?The right-hand side (rhs) of the expression is evaluated before the left-hand side (lhs). So, when the value for
k2is determine, no assigment to%hashhas yet occurred. In fact,%hashhas not even been created and entered into the scratch pad yet. (%hashis a lexical variable here, so it won’t go into the symbol table.)Why use a variable rather than another method?
Well, there are many ways to initialize a hash with values like this. I would use an intermediate variable if I had a small number of related keys to initialize.
However, if I had to build up many complicated values that depended on many different keys, I’d probably use a data driven approach to initialize the hash. The exact implementation would depend on details I don’t have, but it might look something like this:
For any case where this question arrises, the choice as to what technique to use depends on many details that are special to that instance. So we are left with the necessity to make generic statements. Intermediate variables are one good way approach the OP’s problem. Whether they should be used in his particular case, I can not say.