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 i
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:
my %sayings = ("Hello" => "Hi");
my $key = "Hello";
my $var2 = $sayings{$key};
You can also use eval:
my $var = "Hello";
my $Hello = "Hi";
print "1.$var\n";
my $var2 = eval "\$$var";
print "2.$var2\n";
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.
##############################################################
# This works. But only without "use strict" and on a package (global) variable.
##############################################################
no strict; # BOO! Bad coder!
my $var = "Hello";
$Hello = "Hi"; #Look, ma, GLOBAL VARIABLE! Bad Coder!
print "1.$var\n";
my $var2 = ${$var}; # You could use $$var shorthand
print "2.$var2\n";
# OUTPUT:
# 1. Hello
# 2. Hi
##############################################################
# I meant it about package (global variable)
##############################################################
no strict;
my $var = "Hello";
$Hello = "GLOBAL value";
my $Hello = "Hi";
print "1.$var\n";
my $var2 = ${$var}; # You could use $$var shorthand
print "2.$var2\n";
# OUTPUT - see how we don't get "Hi" on a second line
# If we did not assign "GLOBAL Value" to $Hellp on line 3
# , second line would contain no value at all (e.g. "2.")
# 1. Hello
# 2. GLOBAL value
##############################################################
# And, if you do what you SHOULDA done and used strict:
##############################################################
use strict; # Much better!
my $var = "Hello";
my $Hello = "Hi";
print "1.$var\n";
my $var2 = ${$var}; # You could use $$var shorthand
print "2.$var2\n";
# OUTPUT:
# Global symbol "$Hello" requires explicit package name at line 4.
# Execution aborted due to compilation errors.
P.S. If you simply want to use the value of $Hello
hardcoded 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.