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

Good day everyone, Typical substitute problem Jan have to be replaced by JOO Feb have to be replaced by FOO This both have to be done in one single substitue expression. i.e. s/<org>/<new> Many thanks in anticipation, perl fan

Replies are listed 'Best First'.
Re: Multiple substitute values
by Corion (Patriarch) on Sep 21, 2007 at 09:10 UTC

    Please show us the code you have. A possible approach is:

    use strict; my %repl = ( Jan => 'JOO', Fan => 'FOO', Janu => 'JOOU', ); my $search = join "|", map { qr-\b$_\b- } keys %repl; print "Search regular expression is >>$search<<\n"; my $string = "Jan said: I'm a real Fan of Janus. I call him Janu."; print "$string\n"; $string =~ s/($search)/$repl{$1}/ge; print "$string\n";

    See perlre for further information on /g and /e.

      I don't know if it's better or not but I would try to incorporate the capturing parentheses in the generated pattern rather than having to remember to put them in the substitution later.

      my $search = do { local $" = q{|}; qr{\b(@{ [ keys %repl ] })\b}; };

      It just seems safer to keep everything together.

      Cheers,

      JohnGG

      Are %repl's keys regexp or text?

      If they're regexp, your lookup won't work.

      If they're text, they should be converted to regexps before being included in the combined regexp.

      my $search = join "|", map { qr-\b\Q$_\E\b- } keys %repl;

      Of course, you're better of using Regexp::List.

      use Regexp::List; my $search = Regexp::List->new->list2re(keys %repl);
Re: Multiple substitute values
by Anonymous Monk on Sep 21, 2007 at 09:04 UTC
    
    updates. 
    
    Jan have to be replaced with JOO
    Feb have to be replaced with FOO