Write capital letters in a string using perl

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

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

+6
source share
4 answers

Beware of Unicode, as the direct thing AZ is not very portable for other characters, such as accented capital letters. if you need to process them too, try:

my $result = 0; $result++ while($string =~ m/\p{Uppercase}/g); 
+14
source

Use the tr operator:

 $upper_case_letters = $string =~ tr/AZ//; 

This is a general question, and the tr operator is usually superior to other methods .

+9
source
 sub count { $t = shift; $x = 0; for( split//,$t ) { $x++ if m/[AZ]/; } return $x; } 
+2
source

Single line method:

 $count = () = $string =~ m/\p{Uppercase}/g 

This is based on Stuart Watt's answer , but modified according to the advice that ysth posted in the comments to make it single-line.

0
source

Source: https://habr.com/ru/post/892506/


All Articles