Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in understanding perl tr command with /d

Tags:

perl

translate

I came across the following Perl example on the web.

#!/usr/bin/perl 

$string = 'the cat sat on the mat.';
$string =~ tr/a-z/b/d;

print "$string\n";

result:

b b   b.

Can someone please explain how ?

like image 994
vikas81 Avatar asked Jun 08 '15 13:06

vikas81


People also ask

How to use tr command in perl?

Example. #!/usr/bin/perl -w $string = 'the cat sat on the mat. '; $string =~ tr/a-z/b/d; print "$string\n"; When above code is executed, it produces the following result.

What does tr command do?

The tr command is a Linux command-line utility that translates or deletes characters from standard input ( stdin ) and writes the result to standard output ( stdout ). Use tr to perform different text transformations, including case conversion, squeezing or deleting characters, and basic text replacement.

How do you replace characters with tr?

`tr` command can be used with -c option to replace those characters with the second character that don't match with the first character value. In the following example, the `tr` command is used to search those characters in the string 'bash' that don't match with the character 'b' and replace them with 'a'.


1 Answers

/d denotes delete.

It's quite unusual to do a tr like that because it's confusing.

tr/a-z//d

would delete all 'a-z' characters.

tr/a-z/b/ 

would transliterate all a-z characters to b.

What's happening here though is - because your transliteration doesn't map an equal number of character on each side - anything that doesn't map is deleted.

So what you're effectively doing is:

tr/b-z//d;
tr/a/b/;

E.g. transliterating all the as to bs and then deleting anything else (except spaces and dots).

To illustrate:

use strict;
use warnings;
my $string = 'the cat sat on the mat.';
$string =~ tr/the/xyz/d;

print "$string\n";

Warns:

Useless use of /d modifier in transliteration operator at line 5.

and prints:

xyz cax sax on xyz max.

If you change that to:

#!/usr/bin/perl 
use strict;
use warnings;
my $string = 'the cat sat on the mat.';
$string =~ tr/the/xy/d;

print "$string\n";

You get instead:

xy cax sax on xy max.

And thus: t -> x and h -> y. e just gets deleted.

like image 158
Sobrique Avatar answered Nov 06 '22 05:11

Sobrique