perl中tr的研究

perl中有三種模式  m// ,s///,tr///;
前兩種就很少說了,常常出現。這裏說下tr:
不少人用習慣了s///,發現和tr有不少相同的地方,都是將字符串替換成本身想要的內容。
tr的重要做用在於「轉換」.
 
例如:
大小寫轉化:
$str = "Hello World";
$str =~ tr/a-zA-Z/A-Za-z/;  #這裏是將大寫轉爲小寫,小寫轉化爲大寫
print $str;  #輸出hELLO wORLD

計算字符串的個數:
        $str = "Hello World";
my $count=$str =~ tr/a-z/a-z/;  #這裏只計算小寫字母的出現個數,大寫寫出A-Z
print $count;     # 輸出8

關於tr的修飾符有三個: /c,/d./s
perldoc這樣解釋:
c Complement the SEARCHLIST. 
d Delete found but unreplaced characters. 
s Squash duplicate replaced characters. 

$str = "Hello World";
$str =~ tr/ll/*/c;  #將不是l或者ll所有轉化成*
print $str;  #輸出**ll*****l*
 
$str = "Hello World";
$str =~ tr/ll/*/d; #與c修飾符相反
print $str;  #輸出He**o Wor*d
$str = "Hello World";
$str =~ tr/ll/*/s;  #將連續的ll變爲一個*號
print $str;#輸出He*o Wor*d
相關文章
相關標籤/搜索