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

What I'm trying to do is parse some data and replace any data that is a variable with the proper value, however in the data exists monetary amount which I would like skipped by the regexp, so in that case I formatted the data such that anything non-variable and including a $ would be \$. So I have my data that contains $variables and \$1,000 amounts like so, and I want my regexp to skip any amounts, however it is still trying to evaluate the $1... Here is the regexp that's causing me the trouble: s/\$(\w+)/${$1}/g How should I express that so that it will skip amounts (prceeded by a \) and correctly replace variables with the proper value?

Replies are listed 'Best First'.
Re: regexp trouble...
by Anonymous Monk on Jan 02, 2000 at 20:28 UTC
    I haven't dug around the magic tomes to look for a solid answer, but.. are all the $variables spaced? Are there any cases of embeded variables, i.e. 2 Monkey$pluralSwitch? If all $variables are preceeded by a space, then you can have the expression hunt for " $" explicitly. This will skip each " \$" datum. I guess that would be s/\s\$(\w+)//g Just a lazy Sunday thought. -T
Re: regexp trouble...
by fupjack (Initiate) on Jan 03, 2000 at 07:46 UTC
    This would match all instances of $whatever that wasn't immediately following a \, I think. It wouldn't be the fastest regexp in the world...
    s/[^\\]?\$(\w+)/${$1}/g
    I haven't tested it myself, of course... Text::Template is a CPAN module that may well do everything you need, and more, however.
Re: regexp trouble...
by Ridge (Initiate) on Jan 04, 2000 at 01:24 UTC
    I ended up doing this:
    $Data =~ s/([^\\])\$(\w+)/$1${$2}/g; $Data =~ s/\\\$(\w+)/\$$1/g;
Re: regexp trouble...
by Rhandom (Curate) on Jan 04, 2000 at 19:39 UTC
    Why go to all the trouble of making \$'s? All you need to do is match correct variables. A swap like the following would help (this assumes that you probably won't -- and shouldn't for that matter -- use pattern match memories in your stagnant test ala $1,$2,$3 -- this behaviour is awfully magic and difficult to read).
    $Data =~ s/(\$[a-z\_]\w*)/eval($1)/egi; </pre> Don't worry, this is still secure even with the eval. If your brave, why not also include hashes and arrays in your swaps li +ke the following: <pre> $Data =~ s/(\$[a-z\_][\w\{\}\[\]]*)/eval($1)/egi;
    This isn't strict in the match but it will catch most things like $A{B} and so on. Both of these don't even touch values that look like $6.00.
Re: regexp trouble...
by IndyZ (Friar) on Jan 02, 2000 at 22:54 UTC
    You might consider using a different toke to denote a variable name. I am personally a big fan of the percent sign. Other more uncommon characters like the caret (^) could also be used. =Indyz