my $var = "Hello";
my $Hello = "Hi";
my question is: how can I substitute the value of $Hello in $var?
Here $var contains string “Hello” (there is a variable with same name $Hello). I am looking for a way to substitute it with the value of variable $Hello.
Please let me know how can I do that?
This is discussed in Perl FAQ (7): How can I use a variable as a variable name?.
In short, the answer is: Don’t do it. Use hashes instead.
Longer answer:
A MUCH better and simpler solution would have been to store the values in a hash:
You can also use eval:
As a last resort, you COULD use symbolic references. HOWEVER (as discussed in the FAQ linked above), they ONLY work on global variables and ONLY when `use strict ‘refs“ is not in effect – which it should always be for normal Perl development.
P.S. If you simply want to use the value of
$Hellohardcoded variable, you can do$var2 = $Hello;, but I have a feeling you meant you want to use whichever variable’s name is contained in $var.