in reply to replacing "dynamic" variables

bbfu's answer is what you want, but you might also be interested in the /e modifier to the substitution op.

s/(\${\w+})/find_value_for_var("$1")/e

The above code will find alphaneumerical sequences enclosed in ${}, and then send them to the find_value_for_var() function. Perhaps a more coherent example is

s/(\d+)/$1 + 5/e;

Which will find a sequence of digits, then construct the perl expression for those digits, then an addition operator, and then a five, and then evaluate this code, returning the number that was matched plus five.

-nuffin
zz zZ Z Z #!perl

Replies are listed 'Best First'.
Re: Re: replacing "dynamic" variables
by Jenda (Abbot) on Apr 10, 2004 at 16:50 UTC

    Don't enclose variables in doublequotes!

    s/(\${\w+})/find_value_for_var("$1")/e is better written as s/(\${\w+})/find_value_for_var($1)/e! While in this case the quotes cannot "break" the script, it forces Perl to make an additional copy of the matched string each time the regexp matches.

    I wish "$var" trigered a warning. While I admit there are valid reasons to do that I bet they make up at most 0.01% of the times it's used. :-(

    Jenda
    Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
       -- Rick Osborne

    Edit by castaway: Closed small tag in signature