in reply to Re: using a hash to do substitution?
in thread using a hash to do substitution?

I'd change this subtly (unless you only care to match whole words only) to:
$regex = join("|", map(quotemeta, sort { length $b <=> length $a } keys %hash)); s/($regex)/$hash{$1}/eg;
That is, the longer keys will appear first in the alternatives list and thus they will be matched first.


Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain

Replies are listed 'Best First'.
Re: Re: Re: using a hash to do substitution?
by dimmesdale (Friar) on Jun 15, 2001 at 00:18 UTC
    $code .= map { "s/\b$_\b/$hash{$_}/eg;\n" } keys %hash; eval $code;
    This way, you cut the expense of alteration (if the keys are user defined, or you have metachars in them, instead of quotemeta, add \Q and \E before and after, respectively, the first $_ in the substitution). You can print $code to test its values, and by doing it can easily customize it for your specific needs(though if substituting is the only thing going on, this won't be a concern).