Shawn Corey am Montag, 16. Januar 2006 16.55: > John Doe wrote: > > The Ghost am Montag, 16. Januar 2006 06.34: > >>I am storing text stings in a database. when I have the string: > >> > >>'some perl $variable' > >> > >>which would print as: > >> > >>some perl $variable > >> > >>how can I force interpolation of '$variable'? > >> > >>one idea I thought of was: > >>#!/usr/bin/perl > >>my $var='variable'; > >>$string='some $var'; > >>$string=~s/\$(\w+)/${$1}/gi; > >>print "$string\n"; > >> > >>But it doesn't work. I want it to print "some variable". > > > > One way is to change the regex a bit: > > > > #!/usr/bin/perl > > use strict; > > use warnings; > > > > my $var='variable'; > > my $other_var='another'; > > my ($string1, $string2, $string3)=map 'some $var $other_var', 1..3; > > > > # test1, test2, final version: > > # > > $string1=~s/(\$\w+)/$1/g; > > $string2=~s/(\$\w+)/$1/ge; > > $string3=~s/(\$\w+)/$1/gee; > > > > print join "\n", $string1, $string2, $string3; > > > > > > greetings > > joe > > Usually it is considered a bad idea to interpolate external strings. You > could have your users printing any variable. Consider using sprintf > instead (see `perldoc -f sprintf`). > > my $format = 'some perl %s'; > my $string = sprintf $format, $variable; > print "$string\n";
As I understood "The Ghost", the starting point string already contains a literal '$variable': 'some perl $variable'. I do not know the bigger picture of his problem, but I think an extensible way to replace a set of known names within a string by values would be (mirco templating system): === #!/usr/bin/perl use strict; use warnings; my %lookup=( var=>'variable', other_var=>'another', ); sub err {warn q(Unkown name '), shift, qq(' found\n)} my $string='some $var $other_var $unknown'; $string=~s { \$([a-zA-Z_]+) } { exists $lookup{$1} ? $lookup{$1} : do {err($1), ''} }gxe; print $string; === # prints: Unkown name 'unknown' found some variable another No interpolation involved, and the '$' sign preceding the names could be another one. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>