Comparing values in perl

Comparing values in perl

This page shows different ways to compare scalar values in perl. String comparison and numeric comparison are done separately, with one operator for strings and another for numbers.

Comparing numbers

To compare numbers for equality in Perl, use the == operator:

This example, of course, results in:

This numeric not-equal != operator allows you to test for inequality:

If you try to compare strings using ==, and you have included the use warnings pragma, you will get a warning, as in the example below. However, perl will still attempt to convert the string into a number. If the string starts with numbers, perl will use these, otherwise the string equates to 0.

From the above example, you would get warning messages and both strings would evaluate to zero:

Whereas, in the following example the string would equate to 12, although you’d still get a warning:

Output:

It is not recommended that you rely on perl evaluating a string containing numbers and letters as a number.

If you want to check if a number is less than or greater than another number, use the less/greater than (< and >) operators, or the less/greater than equals operators (<= and =>). The following example compares $num1 to different numbers using different operators:

Comparing Strings

To compare two strings use the eq and ne operators. These work much the same as the == and != operators, but they expect the variables to be strings. Here is an example of the eq operator:

This would, of course, print:

A similar example but this time using the ne opeartor:

If you try to compare numbers with eq, they will be converted to strings:

The output of this program would be:

If you want to compare strings to determine which comes first alphabetically, you can use the lt and gt operators, or the le and ge operators for less/greater than equals comparisons. These will compare the strings alphabetically or ‘stringwise’. The following example compares $string1 to different strings using the different methods:

Regular expressions

Much more powerfull comparisons are possible using Perl’s Regular Expressions, which allow you to sompare some input with a pattern. For example, you may want to know if a string contains a number, or if it starts with a certain word.

Regular expressions are covered in great detail in perldoc perlre and perldoc perlretut, and also on this site at Regular Expressions. However, the following examples should give you a basic idea.

The first example checks that a string does not contain any numbers:

And the next example shows how to check if a string contains a phrase like: ‘4 dollars and 25 cents’:

Sorting comparisons

When defining your own sort function, you will need to use the comparison operators. There are two of these: cmp for strings and the spaceship operator <=> for numbers. See the sorting howto and the sorting tutorial.

See also

Scroll to Top