Connecting Tech Pros Worldwide Help | Site Map

Perl Operators

By Blair Ireland
Senior Editor, TheScripts.com

Logical Operators:

And:

$a && $b. The result would be $a if $a is false, and $b otherwise.

Or:

$a || $b. The result would be $a if $a is true, $b otherwise.

Not:

!$a. The result would be true if $a is not true.

Comparison Operators

Equal:

There are two different equal comparison operators for strings and numbers. The numeric equal comparison is == , while the string comparison is eq. The return value would be true if $a is equal to $b.

Not Equal:

The numeric test for two values not being equal is != , while the string test would be ne . The return value would be true if $a is not equal to $b.

Greater Than:

The numeric test for $a being greater than $b would be > while the string test is gt.

Less Than or Equal:

The numeric test for $a being less than or equal than $b would be <= while the string test is le. The return value would be true if $a is less than or equal to $b.

Comparison:

These operators are usually not used, except in a sort routine, which I will explain later on. The numeric comparison is <=> while the string comparison is cmp. The return value would be 0 if equal, 1 if $a is greater, or -1 if $b is greater.

Mathematical Operators

Addition:

$a + $b. The result, obviously, would be the sum of $a and $b.

Subtraction:

$a - $b. As above, this result should be obvious, the difference between $a and $b.

Multiplication:

$a * $b. This result would be the product of $a and $b

Division:

$a / $b. The result would be the dividend of $a and $b.

Modulus:

Not many people know what this means. Basically, the value of this is the remainder between $a divided by $b. It goes in the format $a % $b. This can come in handy if you are looking for even and odd numbers.

Exponentiation:

$a ** $b. This is basically exponents. The example would output the value of $a to the power of $b.

String Operators

It is possible to add strings together. This is known as string concatenation. Perl has a different operator for string concatenation then for regular addition. This operator is the . operator.

For example;

$first = "This";
$second = "is";$third = "fun";print $first . $second . $third;

This would output
Thisisfun

Pretty useless? Well, we can add spaces in there like so;

print $first . " " . $second . " " . $third;

Now this would output
This is fun

You can also multiply strings if you want. Just like the addition operator for strings, it is different then the numeric one. The operator for multiplying strings is x.

For example;

$a = "-";
$b = 10;print $a x $b;

This would output

----------

There, now you know you don't have to write all those dashes out!

« Perl Functions Perl Control Statements »