How do I compare two strings or numbers in Perl (example)
This tutorial explains How to check given two strings are equal or not in Perl.
Perl provides multiple operators to compare strings.
Check whether Two Strings are equal or not in Perl
There are multiple ways we can compare whether strings are equal or not.
use Compare(cmp) operator
cmp
compares two strings in a lexical way, and returns 0,-1,1
operand1 cmp operand2
- Returns 0, if operand1 and operand2 are equal
- Returns -1, if operand1 is less than or equal to operand2
- Returns 1, if operand1 is greater than or equal to operand2
Here is a Perl cmp example In this example, you can check if elseif, else block to test the equality of strings
print 'one' cmp 'one'; # 0
print 'two' cmp 'one'; # 1
print 'one' cmp 'two'; # -1
my $str1 = "two";
my $str2 = "six";
my $result = $str1 cmp $str2;
//
if ($result == 0) {
print "Both are equal.\n";
} elsif ($result < 0) {
print "$str1 is before $str2.\n";
} else {
print "$str1 is after $str2.\n";
}
Perl comparison operators
Perl provides comparison operators as given below.
The above operators work for operand type String.
- eq : equal
- ne : not equal
- lt : less than
- gt : greater than
- le : less than equal
- ge : greater than equal
Here is an example
print 'one' eq 'one'; # 0
print 'two' eq 'one'; # 1
print 'one' eq 'two'; # -1
The below operators work for a given input of numbers.
- == : equal comparison for numbers
- != : not equal check for numbers
Here is an example for a comparison of numbers
print 1 == 1; # 0
print 1 == 2; # 1
print 1 == 0; # -1
An example to check two strings are equal using eq and ne operator
use strict;
use warnings;
my $name1 = "jonh";
my $name1 = "eric";
if ($name1 eq $name2) {
print "equal.\n";
} else {
print "Not equal.\n";
}
if ($name1 ne $name2) {
print "Not equal.\n";
} else {
print "equal.\n";
}
Perl Compare Strings with case sensitive
By Default String comparison in Perl is case insensitive, That means john
and John
are different strings.
You can use the below operators
uc : Upper case Operator lc: lowercase operator
So, to check strings are equal in case insensitive, use uc
or lc
operators to convert to upper or lowercase before comparison.
Here is an example
use strict;
use warnings;
my $name1 = "jonh";
my $name1 = "eric";
if (uc($name1) eq uc($name2)) {
print "equal.\n";
} else {
print "Not equal.\n";
}
if (lc($name1) eq ($name2)) {
print "equal.\n";
} else {
print "Not equal.\n";
}