Embedding code in your pattern: Substitution evaluations and beyond
- When you use the /e modifier on a substitution, the replacement string is actually a perl expression that is evaluated to find the replacement string:
s/\b(\d+\.?\d*)F\b/int(($1 - 32) / 1.8) . "C"/e # Converts Fahrenheit to Celcius
- You can have the replacement string evaluated multiple times by tacking on extra 'e's to the modifier. The following are equivalent:
s/PATTERN/CODE/ee
s/PATTERN/eval(CODE)/e
- Using (?{}) you can also evaluate code. Normally, the return status of this code is ignored, but you can wrap that around a conditional (?(COND)TRUE|FALSE) and that return status will be used in the conditional:
m/(?(?{ $language eq 'java' }) '\/\/' | '#' )(.*)$/ # Searches for comments in input
- Even easer is to use a match-time pattern interpolation. Using (??{}) you can insert code that evaluates to a pattern which is then incorporated into the regular expression
%comment_sign{ 'java' => '//', 'perl' => '#' };
m/(??{ quotemeta $comment_sign{$language} })(.*)$/ # Same as above
/^ (.+) .? (??{quotemeta reverse $1}) $/xi; # Finds palindromes