* How can I expand variables in text strings?
+ removed an example that used a symbolic reference. The other
example covers that case just fine
+ wrap the s///ee in an eval. If we try to evaluate an undeclared
variable under strict, strict does what it does and stops the
program
* How do I expand function calls in a string?
+ removed reference to "How can I expand variables in text strings?"
They are different beasts.
Index: perlfaq4.pod
===================================================================
RCS file: /cvs/public/perlfaq/perlfaq4.pod,v
retrieving revision 1.56
diff -u -d -r1.56 perlfaq4.pod
--- perlfaq4.pod 3 Nov 2004 22:47:56 -0000 1.56
+++ perlfaq4.pod 18 Dec 2004 18:31:44 -0000
@@ -598,9 +598,6 @@
print "My sub returned @{[mysub(1,2,3)]} that time.\n";
-See also ``How can I expand variables in text strings?'' in this
-section of the FAQ.
-
=head2 How do I find matching/nesting anything?
This isn't something that can be done in one regular expression, no
@@ -949,20 +946,19 @@
=head2 How can I expand variables in text strings?
-Let's assume that you have a string like:
+Let's assume that you have a string that contains placeholder
+variables.
$text = 'this has a $foo in it and a $bar';
-If those were both global variables, then this would
-suffice:
-
- $text =~ s/\$(\w+)/${$1}/g; # no /e needed
-
-But since they are probably lexicals, or at least, they could
-be, you'd have to do this:
+You can use a substitution with a double evaluation. The
+first /e turns C<$1> into C<$foo>, and the second /e turns
+C<$foo> into its value. You may want to wrap this in an
+C<eval>: if you try to get the value of an undeclared variable
+while running under C<use strict>, you get a fatal error.
- $text =~ s/(\$\w+)/$1/eeg;
- die if $@; # needed /ee, not /e
+ eval { $text =~ s/(\$\w+)/$1/eeg };
+ die if $@;
It's probably better in the general case to treat those
variables as entries in some special hash. For example:
@@ -973,9 +969,6 @@
);
$text =~ s/\$(\w+)/$user_defs{$1}/g;
-See also ``How do I expand function calls in a string?'' in this
section
-of the FAQ.
-
=head2 What's wrong with always quoting "$vars"?
The problem is that those double-quotes force stringification--
--
brian d foy, [EMAIL PROTECTED]