Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

[ < ] [ > ]   [ << ] [ 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 4.2 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.

String Versionltlegtgeeqnecmp
Operation Numeric Version Returns
less than < 1 iff. $left is less than $right
less than or equal to <= 1 iff. $left is less than or equal to $right
greater than > 1 iff. $left is greater than $right
greater than or equal to >= 1 iff. $left is greater than or equal to $right
equal to == 1 iff. $left is the same as $right
not equal to != 1 iff. $left is not the same as $right
compare <=> -1 iff. $left is less than $right, 0 iff. $left is equal to $right 1 iff. $left is greater than $right
[an error occurred while processing this directive][an error occurred while processing this directive]

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 ""


 
 
  Published under the terms of the GNU General Public License Design by Interspire