Perl programming: logical comparisons: equals and string equals

During tutoring, you often need to point out the unexpected details of a language. The tutor brings up a point that is relevant to Perl, but not only Perl….

Back in my October 4 post, I used a Perl construct that I will explain here now: specifically, the eq operator. There is also potential connection between today’s post and my one from October 2.

In Perl, you can compare values for equality (using the double equals comparison operator, ==). For example:

#!/usr/bin/perl

$joe=$ARGV[0];

$rob=$ARGV[1];

if($rob==$joe){

print “$rob equals $joe\n\n”;
}

else{

print “$rob not equal to $joe\n\n”;
}

Let’s imagine test.txt is the above program’s name. If it is run from the command line thus:

perl test.txt 4 4

you’ll likely get the output

4 equals 4.

If, on the other hand, you run it with this command:

perl test.txt 4 5

you’ll likely receive the response

5 not equal to 4

So far, all seems pretty straightforward. However, let’s run the program again, with this command:

perl test.txt coffee tea

You’ll likely be greeted with the somewhat controversial statement

tea equals coffee

In Perl, variables that are words (as opposed to numbers) are called strings. A string is written in quotes, such as “coffee”. A string definition might look like

$var1=”coffee”;

Strings, if defined, have a numerical value of “not zero”. The == operator is a numerical comparison; from its point of view, “coffee” and “tea” are equal, both being “not zero”.

To compare “coffee” and “tea” as strings, you need to use the operator eq rather than ==, as follows:

if($rob eq $joe)

If we change the program above, replacing

if($rob == $joe)

with

if($rob eq $joe)

it should be able to distinguish between “coffee” and “tea”. If we run it like this:

perl test.txt coffee tea

We should now receive the reassuring response

tea not equal to coffee

Various computer languages treat strings and comparisons in possibly different ways. The important point is that a given language might have its own, unexpected way of handling them. Being aware of that possibility, the programmer is better prepared:)

Source: Robert’s Perl Tutorial

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply