in reply to multi find/replace

You could do something like the following:
my %changes = ( foo => 'bar', 2003 => 2004, cow => 'pig'); $string = 'foo 2003 cow cow 2003 foo whatever'; $string =~ s/(foo|2003|cow)/$changes{$1}/g; print $string; __END__ bar 2004 pig pig 2004 bar whatever

-enlil

Replies are listed 'Best First'.
Re: Re: multi find/replace
by jbware (Chaplain) on Feb 10, 2004 at 21:21 UTC
    Ah, beat me to the punch :) If you wanted to make sure you don't miss any matches in case you modify the hash in the future, you could make the following mods to Enlil's code:
    ... my $changeList = join('|',(keys %changes)); ... $string =~ s/($changeList)/$changes{$1}/g;


    -jbWare

      In case you want the keys to include meta-characters that you don't want to treat as such, you might want to "protect" them:

      #!/usr/bin/perl -w use strict; my %changes=( foo => 'toto', bar => 'tata', 'fo*' => 'to*', ); my $changeList = join('|', map { "\Q$_\E"} keys %changes); my $string= "foo bar fo*"; $string =~ s/($changeList)/$changes{$1}/g; print $string;

      This way $changeList looks like (\Qkey1\E|\Qkey2|...), which instructs the regexp engine to treat everything between \Q and \E as a literal.