I want to count the number of upper case letters in a string using perl.
For 开发者_StackOverflow社区example: I need to know how many upper case characters the word "EeAEzzKUwUHZws" contains.
Beware of Unicode, as the straight A-Z thing isn't really portable for other characters, such as accented uppercase letters. if you need to handle these too, try:
my $result = 0;
$result++ while($string =~ m/\p{Uppercase}/g);
Use the tr
operator:
$upper_case_letters = $string =~ tr/A-Z//;
This is a common question and the tr
operator usually outperforms other techniques.
sub count {
$t = shift;
$x = 0;
for( split//,$t ) {
$x++ if m/[A-Z]/;
}
return $x;
}
The one-liner method is:
$count = () = $string =~ m/\p{Uppercase}/g
This is based off Stuart Watt's answer but modified according to the tip that ysth posted in the comments to make it a one-liner.
精彩评论