Online Learning Applications for Technical English


Home
Syllabus
Assignments

Instructor



Producing Homepages

The s (substitution) function will substitute characters in a string. The format is:
  s/string to search/string to substitute/;
For example:
  $_ = "ABCABCABC";     # $_, Perl's default variable
  s/ABC/abc/;           # One substitution only, 
                        #  result is "abcABCABC"
  s/ABC/abc/g;          # Global substitution,
                        #  result is "abcabcabc"
  $_ = "Input    data\t with     extra whitespace.";
  s/\s+/ /g;            # Collapse whitespace into 
                        #  a single space, globally.
  $_ = "abcAbcaBc";
  s/abc/ABC/gi;         # Global, case insensitive
                        #  substitution, result is
                        #  "ABCABCABC"
  $field =~ s/%(..)/pack("c", hex($1))/ge;

In the last example, we search for '%' followed by two wildcard '.' characters in the target $field. The /e modifier indicates that the string to substitute is the result of the pack function, not the string 'pack("c", hex($1))'. $1 contains the string matching the wildcards (..).

Note 1: You can specify a target string with the binding operator (=~). Otherwise, Perl's default string, $_, is assumed to be the target.

[ Back ]