http://www.perlmonks.org?node_id=741871

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

O wise Perl monks,

I have written a script that parses a file and applies a number of text substitutions. I have a dictionary (let's call it %patdic) of search/substitute pairs and, for each input text line, I run something like

foreach my $search (keys %patdic) { s/$search/$patdic{$search}/g; }

This works well as long as $patdic{$search} does not contain the $1 construct. Consider the following example:

#!/usr/bin/env perl use strict; use warnings; $_=q{nell'amaca}; my $search=q{nell'([[:alpha:]]+a)}; my $subst='na $1'; s/$search/$subst/g; print; print "\n";

This will return "na $1", while I would like it to return "na amaca". Any pointers, please?

Replies are listed 'Best First'.
Re: Evaluating $1 construct in literal replacement expression
by balakrishnan (Monk) on Feb 06, 2009 at 14:48 UTC
    Using eval, you can achieve your need,
    $_=q{nell'amaca}; my $search=q{nell'([[:alpha:]]+a)}; my $subst='na $1'; $expr = "s/$search/".eval $subst."/g"; eval $expr; print; print "\n";
    First we are constructing the substitution, in that using the eval, the substitute pattern is evaluated. And then the total substitution has been evaluated.

    I hope this would match your requirement.
Re: Evaluating $1 construct in literal replacement expression
by jwkrahn (Abbot) on Feb 06, 2009 at 12:16 UTC
      If you mean for example expand "abc $var xyz" so that the string $var is replaced by the value of $var then eval is the only way I know.

      my $var = "123"; my $str = 'abc $var def'; my $temp = eval " \"$str;\" "; print "str2:$temp\n";
Re: Evaluating $1 construct in literal replacement expression
by Anonymous Monk on Feb 06, 2009 at 11:57 UTC
    You may find one of these useful s/$search/na $1/g; s/$search/sprintf '%s',"na $1"/ge;
      So much for previews !

      #s/$search/na $1/g;

      s/$search/sprintf '%s',"na $1"/ge;

        Pls ignore the ramblings above

        This works

        s/$search/$search="na $1"/ge;
Re: Evaluating $1 construct in literal replacement expression
by AnomalousMonk (Archbishop) on Feb 06, 2009 at 18:07 UTC
Re: Evaluating $1 construct in literal replacement expression
by gone2015 (Deacon) on Feb 06, 2009 at 16:22 UTC

    How about:

    my $s ; s/$search/$subst/g and $s = $1 and s/\$1/$s/g ;