- 01Setting up (what you'll need)
- 02Your first output (print)
- 03Variables (scalar variables, $)
- 04Branching (the if statement)
- 05Repeating (the for loop)
- 06Writing a subroutine (a function)
- 07Repeating (the while loop)
- 08Working with arrays (@)
- 09Working with hashes (%)
- 10Regular expression matching
- 11Substitution with regular expressions (s///)
- 12Working with strings
- 13References
- 14Anonymous subroutines
- 15File input and output, the basics
- 16Modules and use strict / warnings
- 17The ternary operator
- 18Sorting (sort)
- 19Packages and the basics of object orientation
- 20[Project] Build a small inventory system
Substitution with regular expressions (s///)
This lesson covers the s/// operator, which replaces text using a regular expression.
Writing $string =~ s/search_pattern/replacement/; replaces the part that matches the pattern with another string.
The sample code writes $text =~ s/Error/ERROR/g; to replace every occurrence of "Error" in the string with "ERROR". The trailing g is the option meaning "replace every match".
A common early stumble is forgetting the g option. Without it only the first match found is replaced, and everything after it is left alone.
In professional work, this substitution is used daily for tidying up logs and for rewriting particular strings throughout a text file in one pass.
๐งช This site can't compile or run Perl directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ nothing is sent anywhere).
