
davorg
Thaumaturge
/ Moderator
Jul 31, 2006, 5:44 AM
Post #4 of 5
(324 views)
|
|
Re: [BenjaminB] replace substrings from array
[In reply to]
|
Can't Post
|
|
So a basic approach would be something like:
# Read this in from the database my %trans = ( 'Eric' => 'Erich', 'Tom' => "Roger", 'food' => 'feet', ); my $text = q(Eric is sitting in a tree eating Tom's food); foreach (keys %trans) { $text =~ s/\b$_\b/$trans{$_}/; } print $text; Note I put used \b in the regex to ensure that we only change whole words. A more sophisticated approach would be to build up a regex containing all of the words to be replaced.
my %trans = ( 'Eric' => 'Erich', 'Tom' => "Roger", 'food' => 'feet'. ); my $regex = '\b(' . join('|', keys %trans) . ')\b'; my $text = q(Eric is sitting in a tree eating Tom's food); $text =~ s/$regex/$trans{$1}/g; print $text; You could use a benchmark to see which is the fastest. -- Dave Cross, Perl Hacker, Trainer and Writer http://www.dave.org.uk/ Get more help at Perl Monks
|