6

I want to count the number of upper case letters in a string using perl.

For example: I need to know how many upper case characters the word "EeAEzzKUwUHZws" contains.

Ben Millwood
  • 6,754
  • 24
  • 45
yohan.jayarathna
  • 3,423
  • 13
  • 56
  • 74

4 Answers4

15

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);
Stuart Watt
  • 5,242
  • 2
  • 24
  • 31
  • 6
    or just `$result = () = $string =~ m/\p{Uppercase}/g` – ysth Jul 11 '11 at 18:19
  • 2
    Do remember that `Uppercase` (alias `upper`) comprises more than merely `Uppercase_Letter` (alias `Lu`), although the former is more often appropirate than the latter is. Both, of course, ignore titlecase when those are distinct from uppercase. – tchrist Jul 12 '11 at 23:20
9

Use the tr operator:

$upper_case_letters = $string =~ tr/A-Z//;

This is a common question and the tr operator usually outperforms other techniques.

Community
  • 1
  • 1
mob
  • 117,087
  • 18
  • 149
  • 283
  • 1
    Well sure, but if you don’t care whether it gets the right answer or not, I can make any bit of code infinitely fast. ;( – tchrist Jul 12 '11 at 23:18
2
sub count {
  $t = shift;
  $x = 0;   
  for( split//,$t ) {
    $x++ if m/[A-Z]/;
  }
  return $x;
}
zellio
  • 31,308
  • 1
  • 42
  • 61
0

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.

Community
  • 1
  • 1
Ben Lee
  • 52,489
  • 13
  • 125
  • 145