Expanding Variables in User Input
Problem
You’ve read in a string with an embedded variable reference, such as:
You owe $debt to me.
Now you want to replace $debt in the string with
its value.
Solution
Use a substitution with symbolic references if the variables are all globals:
$text =~ s/\$(\w+)/${$1}/g;But use a double /ee
if they might be lexical
(my) variables:
$text =~ s/(\$\w+)/$1/gee;
Discussion
The first technique is basically “find what looks like a
variable name, and then use symbolic dereferencing to interpolate its
contents.” If $1 contains the string
somevar, then ${$1} will be
whatever $somevar contains. This won’t work
if the use
strict
'refs' pragma is in effect because
that bans symbolic dereferencing.
Here’s an example:
use vars qw($rows $cols);
no strict 'refs'; # for ${$1}/g below
my $text;
($rows, $cols) = (24, 80);
$text = q(I am $rows high and $cols long); # like single quotes!
$text =~ s/\$(\w+)/${$1}/g;
print $text;
I am 24 high and 80 longYou may have seen the /e
substitution modifier used to evaluate
the replacement as code rather than as a string. It’s designed
for situations such as doubling every whole number in a string:
$text = "I am 17 years old"; $text =~ s/(\d+)/2 * $1/eg;
When Perl is compiling your program and sees a /e
on a substitute, it compiles the code in the replacement block along
with the rest of your program, long before the substitution actually
happens. When a substitution is made, $1 is replaced with the string that matched. The code to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access