當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Perl tr用法及代碼示例


中的 tr 運算符珀爾將SearchList的所有字符轉換為ReplacementList的相應字符。
這裏SearchList是給定的輸入字符,其將被轉換成替換列表中給定的相應字符。

用法: tr/SearchList/ReplacementList/

返回:替換或刪除的字符數

示例 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.



相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 Perl | tr Operator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。