Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between tr/// and s/// when using regex in Perl?

Tags:

regex

perl

I was wondering when one should use s/// over tr/// when working with regular expressions in Perl?

like image 735
user439199 Avatar asked Sep 03 '10 17:09

user439199


People also ask

What is S in Perl regex?

The Substitution Operator The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is − s/PATTERN/REPLACEMENT/;

What does TR mean in Perl?

The tr operator in Perl translates all characters of SearchList into the corresponding characters of ReplacementList. Here the SearchList is the given input characters which are to be converted into the corresponding characters given in the ReplacementList.

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".

How do I match a pattern in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.


3 Answers

s/// is for substitution:

$string =~ s/abc/123/;

This will replace the first "abc" found in $string with "123".

tr/// is for transliteration:

$string =~ tr/abc/123/;

This will replace all occurrences of "a" within $string with "1", all occurrences of "b" with "2", and all occurrences of "c" with "3".

like image 126
CanSpice Avatar answered Oct 18 '22 20:10

CanSpice


tr/// is not a regular expression operator. It is suitable (and faster than s///) for substitutions of one single character with another single character, or (with the d modifier) substituting a single character with zero characters.

s/// should be used for anything more complicated than the narrow use cases of tr.

like image 28
mob Avatar answered Oct 18 '22 21:10

mob


From perlop: Quote and Quote-like Operators

Note that tr does not do regular expression character classes such as \d or [:lower:]. The tr operator is not equivalent to the tr(1) utility. If you want to map strings between lower/upper cases, see lc and uc, and in general consider using the s operator if you need regular expressions.

like image 8
toolic Avatar answered Oct 18 '22 20:10

toolic