Determine if a string begins with an uppercase character in Perl

I need to make a routine in Perl that determines whether a string starts with an uppercase character. So far, I mean the following:

sub checkCase { if ($_[0] =~ /^[AZ]/) { return 1; } else { return 0; } } $result1 = $checkCase("Hello"); $result2 = $checkCase("world"); 
+6
source share
2 answers

This is almost correct. But [AZ] may not match uppercase characters depending on your locale. It is better to use /^[[:upper:]]/ .

Also, your subroutine calls should not have the $ character in front of them. That is, they should be:

 $result1 = checkCase("Hello"); $result2 = checkCase("world"); 
+4
source

Your code is fine while you remove $ from the front of the subroutine call. A dollar sign indicates a scalar value, and calls should look like

 $result1 = checkCase("Hello"); $result2 = checkCase("world"); 

Your routine is also too long. Matching a regular expression returns true / false, and you use this value to return different true / false values โ€‹โ€‹of 1 or 0 . It is much better to return the result of the regular expression directly.

Finally, if you work outside of ASCII characters, you can use the Unicode category for uppercase letters, which is encoded with \p{Lu} .

I hope this code variation is helpful. I changed the name of the subroutine a bit because the standard practice is to use only lowercase letters and underscores for variables and subroutines. Uppercase letters are reserved for global tables, such as package names.

 sub check_case { $_[0] =~ /^\p{Lu}/ } print check_case('Hello') ? 'YES' : 'NO', "\n"; print check_case('world') ? 'YES' : 'NO', "\n"; 
+8
source

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


All Articles