Halona
Halona

Reputation: 1485

How to compare strings case-sensitively?

The name variable may contain 2 words: template or TEMPLATE. Comparing both words (template and TEMPLATE) to "template" string gives TRUE. For example, the code:

...
@name = split(/_/,$f,2);
print("$name[0]");
if ("$name[0]" == "template"){
    print ("\n lowercase \n"); 
} elsif ("$name[0]" == "TEMPLATE") {
    print ("\n UPPERCASE \n");
}

Results:

template

lowercase

TEMPLATE

lowercase

How to compare strings case-sensitively? Really appreciate your help.

Upvotes: 0

Views: 177

Answers (1)

harmic
harmic

Reputation: 30597

In perl, the == operator is used to make numeric comparisons, while the eq operator is used to make string comparisons.

If $name[0] contains TEMPLATE then this:

($name[0] == "template")

is equivalent to comparing 0 with 0, since a string containing non-numeric data will be co-erced to 0 in a numeric context.

If you run it with warnings (use warnings; at the top of the script) you will see warnings about that.

If you want a case sensitive comparison it is enough to use:

($name[0] eq "template")

As a side issue there is no need to write the LHS as "$name[0]" as you have done.

Upvotes: 4

Related Questions