Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I expand variables in text strings?

Tags:

perl

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 $thing comes out as I want to $this. I want it to come out as I want to run.

like image 223
James Avatar asked Jan 19 '11 15:01

James


People also ask

How do I expand a string in PowerShell?

So, you can use $ExecutionContext. InvokeCommand. ExpandString("$Domain\$User") and voila! You've expanded your string.

How do you use a variable inside a string in PowerShell?

PowerShell has another option that is easier. You can specify your variables directly in the strings. $message = "Hello, $first $last." The type of quotes you use around the string makes a difference.

How do I print a variable in a PowerShell string?

The echo command is used to print the variables or strings on the console. The echo command has an alias named “Write-Output” in Windows PowerShell Scripting language. In PowerShell, you can use “echo” and “Write-Output,” which will provide the same output.


1 Answers

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.

like image 167
Dancrumb Avatar answered Oct 15 '22 18:10

Dancrumb