Perl Advent Calendar 2008-12-22

Egg substitute nog

by Jerrad Pierce

How often have you mangled a document with -inline editing like the first block in our code sample? That's what -i~ is for of course, but if you forget, the damage is done. Often, it may be possible to work around such difficulties as in blocks two and three, but what if you haven't stemmed or grepped all the text in the document to look for possible substr conflicts? You're in a rush and have no desire to muck with boundaries and look-aheads/behinds… You just just want a nice, simple, DWIMmy, explicit text replacement. Regexp::Subst::Parallel to the rescue. subst is a small parser that accepts multiple pairs of strings or regular expressions to locate, and a string or /expr (né CODEREF) to replace matches with. The easy to mistype function then manages to perform the substitutions in a sane manner, regardless of order specified. This code lends itself to solving more complex problems, and can even serve as a basic templating engine.

mod22.pl

   1 use Regexp::Subst::Parallel;
   2 
   3 $_ = "I like apples but I don't like oranges.\n";
   4 
   5 #Off-the-cuff implementation: I like bananas but I don't like pinebananas.
   6 {
   7   local $_=$_;
   8   s/orange/pineapple/g;
   9   s/apple/banana/g;
  10   print;
  11 }
  12 
  13 #Carefully crafted regexp:    I like bananas but I don't like pineapples.
  14 {
  15   local $_=$_;
  16   s/orange/pineapple/g;
  17   s/\bapple/banana/g;
  18   print;
  19 }
  20 
  21 #Considered ordering:         I like bananas but I don't like pineapples.
  22 {
  23   local $_=$_;
  24   s/apple/banana/g;
  25   s/orange/pineapple/g;
  26   print;
  27 }
  28 
  29 #Care-free substitution:      I like bananas but I don't like pineapples.
  30 {
  31   local $_=$_;
  32   print subst($_,
  33 	      'orange'=>'pineapple',
  34 	      'apple' =>'banana');
  35 }
View Source (POD)