my $var = "Hello";
my $Hello = "Hi";
我的问题是:如何在$ var中替换$ Hello的值? 这里$ var包含字符串“Hello”(有一个名为$ Hello的变量)。我正在寻找一种方法用变量$ Hello的值替换它。 请让我知道我该怎么做?
答案 0 :(得分:14)
这在Perl FAQ(7)中进行了讨论:How can I use a variable as a variable name?。
简而言之,答案是:不要这样做。请改用哈希。
更长的答案:
更好更简单的解决方案是将值存储在哈希中:
my %sayings = ("Hello" => "Hi");
my $key = "Hello";
my $var2 = $sayings{$key};
您也可以使用eval:
my $var = "Hello";
my $Hello = "Hi";
print "1.$var\n";
my $var2 = eval "\$$var";
print "2.$var2\n";
作为最后的手段,您可以使用符号引用。然而(正如上面链接的FAQ中所讨论的),它们只适用于全局变量,并且只有当`use strict'refs``不起作用时 - 它应该始终用于正常的Perl开发。
##############################################################
# 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。如果你只想使用$Hello
硬编码变量的值,你可以$var2 = $Hello;
,但我觉得你想要使用$ var中包含的变量名。
答案 1 :(得分:-3)
如果您愿意使用变量值填充字符串中的占位符,可以使用:
my $Hello = "Hi";
my $var = "$Hello world";
# $var is now "Hi world"
如果要替换某些变量名称的每个出现,可以使用:
my $Hello = "Hi";
my $greet = "Hello, my name is Jimbo, and I hate Helloween.";
$greet =~ s/Hello/$Hello/g;
# $greet is now "Hi, my name is Jimbo, and I hate Hiween.";
就像DVK提出的那样,eval也可以部分地解决这个问题:
my $Hello = "Hi";
my $greet = "\$Hello, my name is Jimbo, and I hate \$Helloween.";
$greet = eval "\"$greet\"";
# $greep is now "Hi, my name is Jimbo, and I hate ."
编辑:很抱歉我以前回答的简短,我在候机室的手机上输入了它......