How to compare two strings in Perl?


Perl has methods and operators that determine whether two string values are equal or different. In Perl, the compare strings function is essential for comparing two strings and their values. This check examines if two string values are equal or not by using the "eq" and "ne" operators. We can also compare two strings with the help of the "lt, gt, ge, le" operators as well.

In this tutorial, we will consider all the approaches that can be used to compare two strings in Perl.

The "eq" and "ne" Operators in Perl

Let's start with the eq and ne operators. "eq" is for "equal to" and "ne" is for "not equal to". Consider the code shown below where we are using the "eq" operator and the "ne" operator to compare two strings −

Example

$var1 = "TutorialsPoint";
$var2 = "TutorialsPoint";
$var3 = "Leetcode";
if ($var1 eq $var2) {
   print "String var1 is equal to String var2\n";
} else {
   print "String var1 is not equal to String var2\n";
}
if ($var1 ne $var3) {
   print "String var1 is not equal to String var3\n";
} else {
   print "String var1 is equal to String var3\n";
}

Output

If you run the above code on a Perl compiler, it will produce the following output on the terminal −

string var1 is equal to String var2
string var1 is not equal to String var3 

The "lt", "gt", "ge", and "le" Operators in Perl

Now, let's see how to use the "lt, gt, ge, and le" operators to compare two strings.

  • lt – Less than operator

  • gt – Greater than operator

  • ge – Greater than or equal to operator

  • le – Less than or equal to operator

Example

Consider the code shown below.

$var1 = "TutorialsPoint";
$var2 = "TutorialsPoint";
$var3 = "Leetcode";
if ($var1 lt $var2) {
   print " string var1 is less than to String var2 \n";
}
if ($var1 gt $var3) {
   print "string var1 is greater than to String var3 \n";
}
if ($var2 ge $var3) {
   print "string var2 is greater than or equal to String var3 \n";
}
if ($var2 le $var3) {
   print "string var2 is less than or equal to String var3 \n";
}

Output

In the above code, we used four different operators, namely, lt, gt, ge, and le to compare two strings. If you run the above code on a Perl compiler, it will produce the following output on the terminal −

string var1 is greater than to String var3
string var2 is greater than or equal to String var3

Conclusion

In this tutorial, we used two simple examples to demonstrate how you can use the different built-in operators in Perl to compare two given strings.

Updated on: 04-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements