1.8. Expanding Variables in User InputProblemYou've read in a string with an embedded variable reference, such as: You owe $debt to me.
Now you want to replace SolutionUse a substitution with symbolic references if the variables are all globals: $text =~ s/\$(\w+)/${$1}/g;
But use a double $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 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;
You may have seen the $text = "I am 17 years old"; $text =~ s/(\d+)/2 * $1/eg;
When Perl is compiling your program and sees a 2 * 17 If we tried saying: $text = 'I am $AGE years old'; # note single quotes $text =~ s/(\$\w+)/$1/eg; # WRONG
assuming '$AGE'
which just yields us our original string back again. We need to evaluate the result
again
to get the value of the variable. To do that, just add another $text =~ s/(\$\w+)/$1/eeg; # finds my() variables
Yes, you can have as many
Subsequent
The following example uses the # expand variables in $text, but put an error message in # if the variable isn't defined $text =~ s{ \$ # find a literal dollar sign (\w+) # find a "word" and store it in $1 }{ no strict 'refs'; # for $$1 below if (defined $$1) { $$1; # expand global variables only } else { "[NO VARIABLE: \$$1]"; # error msg } }egx;
Note that the syntax of See Also
The Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|