How can I expand variables in text strings?

I have a Perl script where I read a line from a configuration file that contains the variable name. When I read a line in a variable, the name of the variable that needs to be replaced with this value does not fit. 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 $thing is output as I want to $this . I want it to appear as I want to run .

+4
source share
2 answers

OK, so you want Perl to evaluate your string, not print it.

This is really covered in this FAQ for Perl: How to extend variables in text strings?

In short, you can use the following regular expression:

 $string =~ s/(\$\w+)/$1/eeg; 

CAUTION: Evaluating arbitrary strings from outside your scripts is a serious security risk. A good hacker can use this to execute arbitrary code on your server.

The answer to the question about Brian covers some of them.

+8
source

Use eval :

 print eval $thing; 

Using package variables, you can also use symbolic links :

 $thing =~ s/\$(\w+)/$$1/; 
+3
source

Source: https://habr.com/ru/post/1336155/


All Articles