eWebProgrammer eweb  






Advanced Perl  «Prev  Next»
Lesson 12 Executable replacements
Objective Learn how to execute the replacement part of the substitute operator.
The second part of the substitute operator (the replacement part) can also be executed as code.
You tell Perl to evaluate the string in the right side of the substitute expression by adding the /e switch at the end.
For example, consider the case of a program that reads a file and sends it to the browser. That file can be HTML, of course, but what if it also could contain Perl variables?
Consider this Perl routine:
sub htmlp{
  $filename = shift;
  open(HTMLP, "<$filename");
  while(<HTMLP>) {
    s/$(\w+)//eg;  
    print;
  }
  close HTMLP;
}
The substitute operator first looks for a dollar sign followed by one or more alphanumeric characters using the regular expression, "/$(\w+)/". That will match the syntax of a Perl scalar variable.
Then, the substitution replaces the string with the result of the expression, "//".
The /e switch tells perl to evaluate the right side as an expression.
The $ {expression} syntax says to evaluate expression as the name of a variable and to return the value of that variable.
If you call the above htmlp routine like this:
($browser, $version, $extra) = 
$ENV{'HTTP_USER_AGENT'} =~ m|(\w*)/([\d\w.]*)\s*(.*)|; htmlp("yourfile.html");
 You are using $browser, version $version.
The file sent to the browser would have the variables replaced with the values they got from the Perl script, so your browser screen would say something like this:
You are using Version: 7.0.6.001.18000
This is just some of the power of regular expressions in Perl.
Additional regular expressions will be used for the remainder of this course.
Substitute Operator - Exercise
Click the Exercise link below to practice using the s/ operator in an automated spelling checker.
Substitute Operator - Exercise