%change = qw( green yellow blue red ); my $rx = join '|', # alternation map { quotemeta } # make it a safe string sort { length($b) <=> length($a) } # so that 'broken' matches before 'broke' keys %change; $str =~ s/($rx)/$change{$1}/g;