in reply to how do I use s///e

In a templating system a substitution of this form can be used to do a lookup on variables being substituted with replacement from a pre-populated hash.
my %myHash = (hello=>"Howdy", goodbye=>"See ya"); while (<DATA>) { s/\$(\w+)/$myHash{$1}/eg; print; } __DATA__ When I want to say hello I say $hello. When I want to say goodbye I say $goodbye!

Update Whoops! Thanks Abigail! This started as an example that used a sub to do the look up in a database but I got all lazy and just did it as a hash. Some revised (incomplete) code below.

s/\$(\w+)/dbLookup($1)/eg; sub dbLookup { # Do database lookup (which would take a few more lines!) return $lookedup ? $lookedup : ''; }

Replies are listed 'Best First'.
Re: how do I use s///e
by Abigail-II (Bishop) on Jan 26, 2004 at 17:43 UTC
    There's no point in using /e in your code. Removing the /e yields the same results.

    Abigail

      To expand on this, whenever you have a (update: just) variable in the substitution, it's as if you said /e. In a sense, then, /e just becomes syntactic sugar that you can do away with:
      $ echo with bright knives he releaseth my soul | perl -wpe's/(\w+)/${\ +ucfirst($1)}/g' With Bright Knives He Releaseth My Soul