in reply to search and replace from array values

Here's my go. Similar to davidrw's but uses the e modifier (treats the right hand side as an expression).

#!/bin/perl5 use strict; use warnings; my @search = ("red", "orange", "blue"); my @replace = ("yellow", "black", "green"); my %replacements; @replacements{ @search } = @replace; my $string = q(red orange blue blue); for my $key (keys %replacements){ $string =~ s/$key/$replacements{$key}/ge; }

Replies are listed 'Best First'.
Re^2: search and replace from array values
by Roy Johnson (Monsignor) on Dec 06, 2005 at 15:14 UTC
    The major difference is that your loop makes multiple passes through the string, and davidrw's does not. Depending on the size of the string and how many search terms there are, the performance difference can be quite significant.

    Caution: Contents may have been coded under pressure.