当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Perl cmp用法及代码示例

Perl 中的 cmp 运算符是字符串相等比较运算符,用于比较该运算符左右两个字符串是否等于或小于另一个。

用法: string1 cmp string2

返回:如果 string1 小于,则为 -1;如果等于,则为 0;如果大于 string2,则为 1。

示例 1:当 String1 小于 String2 时


#!/usr/local/bin/perl 
  
# Initializing strings 
$a = "Geeks"; 
$b = "Welcome"; 
  
# Comparing strings 
$c = $a cmp $b; 
  
# Printing the comparison result 
print("Comparison of \$a and \$b returns $c"); 
输出:
Comparison of $a and $b returns -1

示例 2:当 String1 等于 String2 时


#!/usr/local/bin/perl 
  
# Initializing strings 
$a = "Welcome"; 
$b = "Welcome"; 
  
# Comparing strings 
$c = $a cmp $b; 
  
# Printing the comparison result 
print("Comparison of \$a and \$b returns $c"); 
输出:
Comparison of $a and $b returns 0

示例 3:当 String1 大于 String2 时


#!/usr/local/bin/perl 
  
# Initializing strings 
$a = "Welcome"; 
$b = "Geeks"; 
  
# Comparing strings 
$c = $a cmp $b; 
  
# Printing the comparison result 
print("Comparison of \$a and \$b returns $c"); 
输出:
Comparison of $a and $b returns 1


相关用法


注:本文由纯净天空筛选整理自Code_Mech大神的英文原创作品 Perl | cmp Operator。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。