Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a string starts with an upper-case character in Perl

I need to make a subroutine in Perl which determines if a string starts with an upper-case character. What I have so far is the following:

sub checkCase {
    if ($_[0] =~ /^[A-Z]/) {
        return 1;
    }
    else {
        return 0;
    }
}

$result1 = $checkCase("Hello");
$result2 = $checkCase("world");
like image 944
Dan Jones Avatar asked May 18 '13 17:05

Dan Jones


People also ask

How do you check if a character is an uppercase letter?

isupper() – check whether a character is uppercase.

How do you check if a string is upper?

The string isupper() method returns True if all cased characters in a string are uppercase. Otherwise, it returns False . If the string doesn't contain any cased characters, the isupper() method also returns False .

How do you check if a character is upper or lower?

Find the ASCII value of the character. If the ASCII value of the character is between 65 and 90, print "Upper". If the ASCII value of the character is between 97 and 122, print "Lower". If the ASCII value of the character is between 48 and 57, print "Number".


2 Answers

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

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

Your subroutine is also unnec essarily long. The regex match returns a true/false value, and you are using that value to return different true/false values 1 or 0. Much better to return the result of the regex match directly.

Finally, if you are working outside ASCII characters then you may want to use the Uppercase Letter Unicode category, which is encoded using \p{Lu}.

I hope this variation on your code is useful. I have changed the name of the subroutine slightly because it is standard practice to use just lower case letters and underscores for variable and subroutine identifiers. Upper case letters are reserved for globals like package names.

sub check_case {
  $_[0] =~ /^\p{Lu}/
}

print check_case('Hello') ? 'YES' : 'NO', "\n";
print check_case('world') ? 'YES' : 'NO', "\n";
like image 96
Borodin Avatar answered Sep 22 '22 23:09

Borodin


That's almost correct. But [A-Z] might not match uppercase accented characters depending on your locale. Better to use /^[[:upper:]]/.

Also your subroutine invocations shouldn't have the $ character in front of them. I.e. they should be:

$result1 = checkCase("Hello");
$result2 = checkCase("world");
like image 42
simonp Avatar answered Sep 22 '22 23:09

simonp