in reply to Replace placeholders in text in an elegant manner

Or perhaps something like this?
use strict; use warnings; my $text = join '', <DATA>; my %replacements = ( 'Romeo' => 'CountZero', 'Juliet' => 'Elisabeth', 'Rom.' => 'CountZero', 'Jul.' => 'Elisabeth', 'Abram' => 'Igor', 'Abr.' => 'Igor', ); $text =~s/(Romeo|Juliet|Rom\.|Jul\.|Abram|Abr\.)/$replacements{$1}/gi; print $text; __DATA__ (follows the full Project Gutenberg e-text of Shakespeare's Romeo and +Juliet; found at http://www.gutenberg.org/dirs/etext97/1ws1610.txt)
And in a few seconds Perl just made a new masterpiece called "CountZero and Elisabeth".

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: Replace placeholders in text in an elegant manner
by explodec14 (Novice) on Feb 27, 2010 at 20:32 UTC
    You're right on the money!!
    Couldn't be more precise!!

    You're way of solution realy amazed me. Thank you very much.

    PS: I loved your Geoffrey James quotation too!

      There is a gotcha with the solution as written (well, several actually) - you need to provide every possible (or at least likely) case variation for each of the matched words. Combining the special markup you have alluded to elsewhere with the e flag for the regex gives a somewhat more robust solution:

      use strict; use warnings; my $text = join '', <DATA>; my %replacements = ( 'romeo' => 'CountZero', 'juliet' => 'Elisabeth', 'rom.' => 'CountZero', 'jul.' => 'Elisabeth', 'abram' => 'Igor', 'abr.' => 'Igor', ); $text =~s/%%([^%]+)%%/replace($1)/ge; print $text; sub replace { my ($needle) = @_; return "%%$needle%%" if ! exists $replacements{lc $needle}; return $replacements{lc $needle}; } __DATA__ (follows the full Project Gutenberg e-text of Shakespeare's %%Romeo%% +and %%Juliet%%; found at http://www.gutenberg.org/dirs/etext97/1ws1610.txt)

      Prints:

      (follows the full Project Gutenberg e-text of Shakespeare's CountZero +and Elisabeth; found at http://www.gutenberg.org/dirs/etext97/1ws1610.txt)

      True laziness is hard work