in reply to Resolving Imbedded Variables

Here's one way...

my $string = 'foo: $foo and bar: $bar\n'; print $string, "\n"; my $foo = "foozleberry pie"; my $bar = "barzleberry foo"; print eval 'qq(' . $string . ')';
In other words, just take your string and eval it as a double quoted string.

Another technique which is a little less prone to error is to use a hash and perform a substitution on it. In this case, your placeholders only look like perl variables...

my %vars = ( foo => 'foozleberry pie', bar => 'barzleberry foo', ); my $string = 'foo: $foo and bar: $bar'; $string =~ s/\$(\w+)/$vars{$1}/g; print $string, "\n";

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re^2: Resolving Imbedded Variables
by Roy Johnson (Monsignor) on Nov 07, 2005 at 18:03 UTC
    A technique similar to your hash suggestion can make the eval approach secure from code-insertion mischief (I'm guessing this is what you meant by "prone to error"):
    my $string = 'foo: $foo and bar: $bar\n'; print $string, "\n"; my $foo = "foozleberry pie"; my $bar = "barzleberry foo"; $string =~ s/(\$\w+)/$1/gee; print $string, "\n";
    Update: A hash is still a better choice because it automatically restricts which variables will be substituted to a set that you specify, which is almost surely desirable.

    Caution: Contents may have been coded under pressure.