Main Content

Perl substitute - the e modifier

Archive - Originally posted on "The Horse's Mouth" - 2008-12-16 07:58:51 - Graham Ellis

Here's a graphic illustration of the use of the "e" for "execute" modifier used on the end of substitute operation in Perl.

The "s" for substitute allows you to replace a matched pattern with a STRING in which you can use special references like or for the first matched substring. If you want it to replace the matched pattern with the RESULT OF RUNNING CODE, you should add that extra e on the end.

In this example, the $emma variable ends up containing a corrupted email address which actually includes some code, whereas (with the "e"), the $emily variable results in a correct email address with the section before the "@" pushed to lower case.

$emma = 'Graham@wellho.net';
$emily = 'Graham@wellho.net';
 
$emma =~ s/(\w+)@/lc()."@"/;
$emily =~ s/(\w+)@/lc()."@"/e;
 
print ("$emma\n$emily\n");
 
__END__
 
Dorothy:plpw grahamellis$ perl swithe
lc(Graham)."@"wellho.net
graham@wellho.net
Dorothy:plpw grahamellis$