I found this example in a Perl tutorial, but could not understand the output. The tutorial says:
The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST.
but I could not figure out how this is realized in the example.
Can somebody explain how the output was generated?
Script:
$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;
print "[$string]\n";
Output:
[ b b b.]
(The square brackets mark the start and end of the string, that's all.)
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.
=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {
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.
$1 equals the text " brown ".
Since there is only one character in the replacement list (b
), only the first character in the searchlist (a
) will be replaced with b
. The rest of characters in the search list (b-z
) will be deleted.
Hence, replacing a
s with b
s and b-z
letters with nothing,
the cat sat on the mat.
becomes b b b.
(there are only three a
s in the sentence and the spaces and the dot are preserved as they were not part of the searchlist).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With