How do I compare two strings or numbers in Perl with an example
This tutorial explains How to check given two strings are equal or not in Perl
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, 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
print 'one' cmp 'one'; # 0 print 'two' cmp 'one'; # 1 print 'one' cmp 'two'; # -1
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 given input of numbers.
- == : equal comparision for numbers
- != :not equal check for numbers
Here is an example for comparison of numbers
print 1 == 1; # 0 print 1 == 2; # 1 print 1 == 0; # -1