LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl Regexp search-n-replace (https://www.linuxquestions.org/questions/programming-9/perl-regexp-search-n-replace-333972/)

jpbarto 06-15-2005 03:04 PM

Perl Regexp search-n-replace
 
I have a hash of strings containing patterns (keys) and replacement strings (values). Normally, in perl, when you execute:

s/<regexp pattern>/repstr $1 $2/g

$1 and $2 will be replaced with whatever was matched in the regexp (provided the regexp contained parens for grouping). However when I place a replacement string such as 'repstr $1 $2' into the hash and then retrieve it to be placed into the s///g the $1,$2,... gets lost.

I have tried a couple different tricks to try to get 's///g' to evaluate the replacement string but I can't convince it. How do I fix this?

TIA,
jpbarto

Chrax 06-16-2005 10:12 AM

This is a major problem with perl, one that is to be resolved in Perl6.

That said, I have a couple suggestions:
Have you tried backslashing the dollar signs? Then it won't (rather shouldn't... I haven't had this particular perl experience) evaluate them until you call it. But I doubt that will work. There is a way to evaluate perl code in a regular expression, but I can't recall it. I feel it was something like curly braces around the expression, but don't trust me there.

Next perhaps it would work to eval the entire expression.
Code:

while(($key,$value) = each %hash){
    eval{
        $string = s/$key/$value/g;
    }
}

Then again, I'm terrible at doing evals, so if that works char for char, I'll be damned.

Either way, assuming the hash is the only way to go, I think an eval of some sort is your best bet.

I'm sorry I'm so unhelpful. You really picked one of the aspects of perl that I can't quite get a hold on. Hopefully someone can come along who's better at those than I am.

keefaz 06-16-2005 12:45 PM

Quote:

I'm sorry I'm so unhelpful
No, you have the idea

The script should be like :
PHP Code:

foreach $key (keys %hash) {
    
$replace $hash{$key};
    eval 
"\$string=~s/$key/$replace/g";


Note the "\$string" syntax so it does not try to replace
$string with its value


All times are GMT -5. The time now is 11:47 AM.