DocTaur - intranet directory of reference manuals
Yo-store
books for webmasters

reference manuals search engine

Perl Tutorial Book

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.4.2 Comparison Operators

Comparing two scalars is quite easy in Perl. The numeric comparison operators that you would find in C, C++, or Java are available. However, since Perl does automatic conversion between strings and numbers for you, you must differentiate for Perl between numeric and string comparison. For example, the scalars "532" and "5" could be compared two different ways--based on numeric value or ASCII string value.

The following table shows the various comparison operators and what they do. Note that in Perl "", 0 and undef are false and anything else as true. (This is an over-simplified definition of true and false in Perl. See section A Digression--Truth Values, for a complete definition.)

The table below assumes you are executing $left <OP> $right, where <OP> is the operator in question.

Operation

Numeric Version

String Version

Returns

less than

<

lt

1 iff. $left is less than $right

less than or equal to

<=

le

1 iff. $left is less than or equal to $right

greater than

>

gt

1 iff. $left is greater than $right

greater than or equal to

>=

ge

1 iff. $left is greater than or equal to $right

equal to

==

eq

1 iff. $left is the same as $right

not equal to

!=

ne

1 iff. $left is not the same as $right

compare

<=>

cmp

-1 iff. $left is less than $right, 0 iff. $left is equal to $right 1 iff. $left is greater than $right

Here are a few examples using these operators.

 
use strict;
my $a = 5; my $b = 500;
$a < $b;                 # evaluates to 1
$a >= $b;                # evaluates to ""
$a <=> $b;               # evaluates to -1
my $c = "hello"; my $d = "there";
$d cmp $c;               # evaluates to 1
$d ge  $c;               # evaluates to 1
$c cmp "hello";          # evaluates to ""

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated on July, 31 2004 using texi2html 1.70.