cghost23 has asked for the wisdom of the Perl Monks concerning the following question:

hey, i have been using the expression (?<!\\)\$[a-zA-Z0-9_]+ to match all variable names in a perl script, except those whose name is escaped ("\$blah"), and it works fine, but i wanted to turn it into a substition (the script is supposed to change variable names in a perl script) and have each instance of a variable replaced with the output of a subroutine which accepts the matched text as it's argument and mixes the characters around...however, i tried s/(?<!\\)\$[a-zA-Z0-9_]+/change_name($&)/ge and it didnt seem work. (i understand '$&' holds the last matching text..and after reading some example code, i also tried '$1'...to no avail)..the code segment is
while (<FILENAME>) { s/(?<!\\)\$[a-zA-Z0-9_]+/change_name($&)/ge; }
and change_name()'s return value is the altered text. thanks in advance, moe

Replies are listed 'Best First'.
Re: substition problem
by Masem (Monsignor) on Apr 21, 2001 at 17:55 UTC
    Why not try:
    s/(?<!\\)(\$[a-zA-Z0-9_]+)/change_name($1)/ge;
    (note, using the placeholder around the variable name at this point, so that what matches should fall into $1).
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
(ar0n) Re: substition problem
by ar0n (Priest) on Apr 21, 2001 at 17:56 UTC
    Use parentheses to capture the match; this will save it into $1:
    while (<>) { s/((?<!\\)\$[a-zA-Z0-9_]+)/change_name($1)/eg; }
    update: Hmmm... it seems the old guy beat me to it ;-)

    ar0n ]