Home » Perl Basics » 10 - Regular Expressions
10

Substitution

How can you use regular expressions along with substitution?

Regular expressions will also allow you to do substitution. Searching for a string and replacing it by another. The syntax is straight forward and easy to comprehend.

  S/string-to-search-for/string-to-replace-it-for/
  
The substitute function with that syntax will only replace the FIRST instance Perl find.
  $sub = “name name”;
  s/name/lastname ;
  
In that case the result of that substitution would be
“lastname name”
Only the FIRST instance would be changed. In order to change all the Matching string you would need to use the “/g” option at the end of the substitution function.
  $sub = “name name”;
  s/name/lastname/g;
You can also use the substitution function to change variable value directly.
  $variable =~ s/to-be-changed/changed/;