Ad space (banner)
Lesson 11 / 20

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.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช 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).

Ad space (banner)
Ad space (in-article)