📜  珀尔 | cmp 运算符(1)

📅  最后修改于: 2023-12-03 15:27:07.224000             🧑  作者: Mango

Perl | cmp Operator

The Perl cmp operator is a string comparison operator used to compare two strings. It returns -1, 0 or 1 depending on whether the first string is less than, equal to or greater than the second string.

Syntax

The cmp operator is used in the following syntax:

$string1 cmp $string2

Where:

  • $string1 and $string2 are the strings to be compared.

The operator returns -1 if $string1 is less than $string2, 0 if they are equal, and 1 if $string1 is greater than $string2.

Example
my $string1 = "apple";
my $string2 = "banana";

my $result = $string1 cmp $string2;

if ($result == -1) {
    print "$string1 is less than $string2\n";
} elsif ($result == 0) {
    print "$string1 is equal to $string2\n";
} elsif ($result == 1) {
    print "$string1 is greater than $string2\n";
}

Output:

apple is less than banana

In the above example, the cmp operator is used to compare the strings $string1 and $string2. Since $string1 comes before $string2 in alphabetical order, the operator returns -1 and the first if block is executed.

Precedence

The cmp operator has a lower precedence than most other Perl operators. It has the same precedence as the numeric comparison operators (==, !=, <, >, <=, >=) and the lt, le, gt and ge string comparison operators.

Conclusion

The cmp operator is a useful string comparison operator in Perl. It is used to compare two strings and return a value indicating whether the first string is less than, equal to or greater than the second string.