珀尔 | tr 运算符
Perl 中的 tr运算符将 SearchList 的所有字符转换为 ReplacementList 的相应字符。
这里的 SearchList 是给定的输入字符,这些字符将被转换为 ReplacementList 中给定的相应字符。
Syntax: tr/SearchList/ReplacementList/
Return:number of characters replaced or deleted
示例 1:此示例使用 tr运算符将小写字母转换为大写字母。
#!/usr/bin/perl
# Initializing the strings
$string1 = 'gfg is a computer science portal';
$string2 = 'geeksforgeeks';
# Calling tr function
$string1 =~ tr/a-z/A-Z/;
$string2 =~ tr/a-z/A/;
# Printing the translated strings
print "$string1\n";
print "$string2\n";
输出:
GFG IS A COMPUTER SCIENCE PORTAL
AAAAAAAAAAAAA
示例 2:此示例使用 tr运算符将大写字母转换为小写字母。
#!/usr/bin/perl
# Initializing the strings
$string1 = 'GFG IS A COMPUTER SCIENCE PORTAL';
$string2 = 'GEEKSFORGEEKS';
# Calling tr function
$string1 =~ tr/A-Z/a-z/;
$string2 =~ tr/A-Z/p/;
# Printing translated strings
print "$string1\n";
print "$string2\n";
输出 :
gfg is a computer science portal
ppppppppppppp
示例 3:此示例使用 tr运算符将大写形式转换为数字形式。
#!/usr/bin/perl
# Initializing the strings
$string1 = 'GFG IS A COMPUTER SCIENCE PORTAL';
$string2 = 'GEEKSFORGEEKS';
# Calling tr function
$string1 =~ tr/A-Z/0-9/;
$string2 =~ tr/A-Z/5/;
# Printing translated strings
print "$string1\n";
print "$string2\n";
输出 :
656 89 0 29999949 9284924 999909
5555555555555
's'运算符的使用:
's'运算符用于 'tr'运算符的末尾,用于检测给定字符串中的重复字符并将其替换为指定的字符。
例子:
#!/usr/bin/perl
# Initializing the strings
$string1 = 'geeksforgeeks';
$string2 = 'geeksforgeeks';
# Calling tr function
# without appending 's' to 'tr' operator
$string1 =~ tr/ee/e/;
# Appending 's' to 'tr' operator
$string2 =~ tr/ee/e/s;
# Printing translated strings
print "$string1\n";
print "$string2\n";
输出 :
geeksforgeeks
geksforgeks
在上面的代码中,可以看出,当 's' 附加到 'tr'运算符的末尾时,它会用单个“e”替换重复的“e”,即“ee”。
'c'运算符的使用:
'c'运算符用于'tr'运算符的末尾,用于检测给定字符串中的空格('')字符并将其替换为指定的字符。
例子:
#!/usr/bin/perl
# Initializing the strings
$string1 = 'gfg is a computer science portal';
$string2 = 'gfg is a computer science portal';
# Calling tr function
# without appending 'c' to 'tr' operator
$string1 =~ tr/a-z/_/;
# Appending 'c' to 'tr' operator
$string2 =~ tr/a-z/_/c;
# Printing translated strings
print "$string1\n";
print "$string2\n";
输出 :
___ __ _ ________ _______ ______
gfg_is_a_computer_science_portal
在上面的代码中,可以看出在每个单词之间使用了符号下划线(“_”),这是通过附加“c”来完成的。
Note 1: This tr operator does the task of lc() function and uc() function as well as it translates the input characters into numeric form etc.
Note 2: This tr operator is slightly different from y operator because y operator does not use the appending of “c” or “s” to the operator but tr operator does.