in reply to Multiple substitute values

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.

Replies are listed 'Best First'.
Re^2: Multiple substitute values
by johngg (Canon) on Sep 21, 2007 at 10:39 UTC
    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

Re^2: Multiple substitute values
by ikegami (Patriarch) on Sep 21, 2007 at 13:16 UTC

    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);