Perl Matching and substitution
Operatorsm/pattern/gimosx
The “match” operator searches a string for a pattern match. The preceding “m” is usually omitted. The trailing modifiers are as follows
Modifier | Meaning |
---|---|
g | Match globally; find all occurrences |
i | Do case-insensitive matching |
m | Treat string as multiple lines |
o | Only compile pattern once |
s | Treat string as a single line |
x | Use extended regular expressions |
s/pattern/replacement/egimosx
Searches a string for a pattern, and replaces any match with replacement. The trailing modifiers are all the same as for the match operator, with the exception of “e”, which evaluates the right-hand side as an expression. The substitution operator works on the default variable ($_), unless the =~ operator changes the target to another variable.
tr/pattern1/pattern2/cds
This operator scans a string and, character by character, replaces any characters matching pattern1 with those from pattern2.
Trailing modifiers are:
Modifier | Meaning |
---|---|
c | Complement pattern1 |
d | Delete found but unreplaced characters |
s | Squash duplicated replaced characters |
This can be used to force letters to all uppercase:
tr/a-z/A-Z/;
@fields = split(pattern,$input);
Split looks for occurrences of a regular expression and breaks the input string at those points. Without any arguments, split breaks on the whitespace in $_:
@words = split;
@words = split(/\s+/,$_);
$output = join($delimiter,@inlist);
Join, the complement of split, takes a list of values and glues them together with the provided delimiting string.