开发者

Count uppercase letters in string using perl

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜