I have a Perl script where I read in a line from a configuration file that contains a variable name. When I read the line into a variable the variable name that needs to be replaced with the given value is not put in. I am using Config::Tiny to access my configuration file. Example:
configuration file
thing=I want to $this
script
$this = "run";
my $thing = $Config->{thing};
print $thing;
print 开发者_C百科$thing
comes out as I want to $this
. I want it to come out as I want to run
.
OK, so you're wanting Perl to evaluate your string as opposed to print it.
This is actually covered in this Perl FAQ: How can I expand variables in text strings?
In short, you can use the following regular expression:
$string =~ s/(\$\w+)/$1/eeg;
BE CAREFUL: Evaluating arbitrary strings from outside of your scripts is a major security risk. A good hacker can exploit this to execute arbitrary code on your server.
Brian's FAQ answer covers some of this.
Use eval
:
print eval $thing;
With package variables it's also possible to use symbolic references:
$thing =~ s/\$(\w+)/$$1/;
精彩评论