Searching and Replacing
Operator
Syntax
Description
Match Operator
/PATTERN/
Match the given pattern
Match Operator
m/PATTERN/
Match the given pattern
Search & Replace
s/PATTERN/REPLACE/
Search and replace the pattern
Char. S&R
tr/searchlist/replacelist/
Character search and replace
Split
split(/PATTERN/, $line)
Split on regex pattern
The Substitution Operator (s///)
The substitution operator (s///) is used to change strings
IMPORTANT* : **looks like the original text is replaced, and actually the $result simply stores the NUMBER of substitutions made, not the actual result. ** 1 2 3 4 5 6 7 8 9 10 $needToReplace = "bbb" ; $replacementText = "1234567890" ; $_ = "AAA bbb AAA" ; $result = s/$needToReplace/$replacementText/ ; print $_; print "\n" ;print $result;
Options for Substitution Operator
Option
Description
e
Forces Perl to evaluate the replacement pattern as an expression
g
Replaces all occurrences of the pattern in the string
i
Ignores the case of characters in a string
m
Treats string as multiple lines (any \n
will be the end of a single match)
s
Treats string as a single line (treats \n
as any other character)
o
Compiles pattern only once
x
Allows for extended regular expressions (ignores white spaces within the / /)
1 2 3 4 $_ = "home, sweet home!" ; s/home/cave/g ; print "$_\n" ;
removing excessive whitespaces
1 2 3 4 5 6 7 8 9 10 11 12 $_ = " Input data\t may have extra whitespace. " ; print "$_\n" ;s/\s+/ /g ;print "$_\n" ; s/^\s+// ; print "$_\n" ;
1 2 3 Input data may have extra whitespace. Input data may have extra whitespace. Input data may have extra whitespace.