http://qs321.pair.com?node_id=67956

DeusVult has asked for the wisdom of the Perl Monks concerning the following question:

Ok, monks, here is an interesting little problem for you. Suppose you have a scalar, $string, which is a multi-line text string (slurped up a whole file into it). Suppose you also have a hash, let's call it %substitute_hash. The keys of this hash are strings which may or may not appear in $string, but you most certainly do not want them to appear there anymore. Handily enough, the values inside the hash are the things you would rather have in place of those keys.

So, if you had three guys named John, Jack, and Joe who just changed their names to Mike, Mark, and Moe, %substitute_hash might look like this:

%substitute_hash = ( John => Mike, Jack => Mark, Joe => Moe );

Now the problem proper: I would like to write the following regex:

 $string =~ s/(anything which is a key in %substitute_hash/$substitute_hash{the thing found in between the first two /'s}/;

The best thing I can think of is to do the cheap little hackish version:

foreach keys %substitute_hash { $string =~ s/$_/$substitute_hash{$_}; }

I'll do that as a last resort, but the application I need to do this for will involve doing this substitution on many, many files (several dozen, maybe 100+), and %substitute_hash will likely be very big (several hundred entries, maybe even a few thousand), so efficiency is really a factor.

Also, I'm not particularly married to this implementation, so if you can think of a really efficient way of doing this with some other data structure than a hash, that isn't a problem. Thanks in advance.

Some people drink from the fountain of knowledge, others just gargle.