Perl: Operators

The Binary Arithmetic Operators

There are six binary arithmetic operators: addition, subtraction, multiplication, exponentiation (**), division, and modulus (%).

For example, op1.pl:

$x = 3 + 1;
$y = 6 - $x;

$z = $x * $y;

$w = 2**3; # 2 to the power of 3 = 8
The modulus operator is useful when a program needs to run down a list and do something every few 
items. This example shows you how to do something every 10 items, mod.pl: 
for ($index = 0; $index <= 100; $index++) {

if ($index % 10 == 0) {

print("$index ");

}

}
When this program is run, the output should look like the following:
0 10 20 30 40 50 60 70 80 90 100

Notice that every tenth item is printed. By changing the value on the right side of the modulus operator, you can affect how many items are processed before the message is printed. Changing the value to 15 means that a message will be printed every 15 items.

The Unary Arithmetic Operators

In common with C, Perl has two short hand unary operators that can prove useful.

The unary arithmetic operators act on a single operand. They are used to change the sign of a value, to increment a value, or to decrement a value. Incrementing a value means to add one to its value. Decrementing a value means to subtract one from its value.

In many statements we frequently write something like:

$a = $a + 1;

we can write this more compactly as:

$a += 1;.

This works for any operator so this is equivalent:

$a = $a * $b;
$a *= $b;
You can also automatically increment and decrement variables in Perl with the ++ and -- operators.

For example all three expressions below achieve the same result:

$a = $a + 1;
$a += 1;
++$a;

The ++ and -- operators can be used in prefix and postfix mode in expressions. There is a difference in their use.

In Prefix the operator comes before the variable and this indicates that the value of the operation be used in the expression: I.e.

$a = 3;
$b = ++$a;

results in a being incremented to 4 before this new value is assigned to b. That is to say BOTH a and b have the value 4 after these statements have been executed.

In postfix the operator comes after the variable and this indicates that the value of the variable before the operation be used in the expression and then the variable is incremented or decremented: I.e.

$a = 3;
$b = $a++;

results in the value of a (3) being assigned to b and then a gets incremented to 4 That is to that after these statements have been executed b = 3 and a = 4.

The Perl programming language has many ways of achieving the same objective. You will become a more efficient programmer if you decide on one approach to incrementing/decrementing and use it consistently.

The Logical Operators

Logical operators are mainly used to control program flow. Usually, you will find them as part of an if, a while, or some other control statement .

The Logical operators are:

op1 && op2 -- Performs a logical AND of the two operands. op1 || op2 -- Performs a logical OR of the two operands. !op1 -- Performs a logical NOT of the operand.

The concept of logical operators is simple. They allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to a true or false value. Then the value of the conditions is used to determine the overall value of the op1 operator op2 or !op1 grouping. The following examples demonstrate different ways that logical conditions can be used.

The && operator is used to determine whether both operands or conditions are true and.pl.

For example:

if ($firstVar == 10 && $secondVar == 9) {

print("Error!");

};

If either of the two conditions is false or incorrect, then the print command is bypassed.

The || operator is used to determine whether either of the conditions is true.

For example:

if ($firstVar == 9 || $firstVar == 10) {

print("Error!");
If either of the two conditions is true, then the print command is run. 

Caution If the first operand of the || operator evaluates to true, the second operand will not be evaluated. This could be a source of bugs if you are not careful.

For instance, in the following code fragment:

if ($firstVar++ || $secondVar++) { print("\n"); }
variable $secondVar will not be incremented if $firstVar++ evaluates to true. 

The ! operator is used to convert true values to false and false values to true. In other words, it inverts a value. Perl considers any non-zero value to be true-even string values. For example:

$firstVar = 10;

$secondVar = !$firstVar;


if ($secondVar == 0) {

print("zero\n");

};

is equal to 0- and the program produces the following output:

zero

You could replace the 10 in the first line with "ten," \'ten,\' or any non-zero, non-null value.

The Bitwise Operators

The bitwise operators are similar to the logical operators, except that they work on a smaller scale -- binary representations of data.

The following operators are available:

  • op1 & op2 -- The AND operator compares two bits and generates a result of 1 if both bits are 1; otherwise, it returns 0.
  • op1 | op2 -- The OR operator compares two bits and generates a result of 1 if the bits are complementary; otherwise, it returns 0.
  • op1^ op2 -- The EXCLUSIVE-OR operator compares two bits and generates a result of 1 if either or both bits are 1; otherwise, it returns 0.
  • ~op1 -- The COMPLEMENT operator is used to invert all of the bits of the operand.
  • op1 >> op2 -- The SHIFT RIGHT operator moves the bits to the right, discards the far right bit, and assigns the leftmost bit a value of 0. Each move to the right effectively divides op1 in half.
  • op1 << op2 -- The SHIFT LEFT operator moves the bits to the left, discards the far left bit, and assigns the rightmost bit a value of 0. Each move to the left effectively multiplies op1 by 2.

Note Both operands associated with the bitwise operator must be integers.

Bitwise operators are used to change individual bits in an operand. A single byte of computer memory-when viewed as 8 bits-can signify the true/false status of 8 flags because each bit can be used as a boolean variable that can hold one of two values: true or false. A flag variable is typically used to indicate the status of something. For instance, computer files can be marked as read-only. So you might have a $fReadOnly variable whose job would be to hold the read-only status of a file. This variable is called a flag variable because when $fReadOnly has a true value, it\'s equivalent to a football referee throwing a flag. The variable says, "Whoa! Don\'t modify this file."

When you have more than one flag variable, it might be more efficient to use a single variable to indicate the value of more than one flag. The next example shows you how to do this.

Example: Using the &, |, and ^ Operators

The first step to using bitwise operators to indicate more than one flag in a single variable is to define the meaning of the bits that you\'d like to use. Figure shows an example of 8 bits that could be used to control the attributes of text on a display.

The bit definition of a text attribute control variable

If you assume that $textAttr is used to control the text attributes, then you could set the italic attribute by setting $textAttr equal to 128 like this:

$textAttr = 128;

because the bit pattern of 128 is 10000000. The bit that is turned on corresponds to the italic position in $textAttr.

Now let\'s set both the italic and underline attributes on at the same time. The underline value is 16, which has a bit pattern of 00010000. You already know the value for italic is 128. So we call on the OR operator to combine the two values.

$textAttr = 128 | 16;

or using the bit patterns (this is just an example-you can\'t do this in Perl)

$textAttr = 10000000 | 00010000;
You will see that $textAttr gets assigned a value of 144 (or 10010000 as a bit pattern). 
This will set both italic and underline attributes on. 

The next step might be to turn the italic attribute off. This is done with the EXCLUSIVE-OR operator, like so:

$textAttr = $textAttr ^ 128;

Example: Using the >> and << Operators

The bitwise shift operators are used to move all of the bits in the operand left or right a given number of times. They come in quite handy when you need to divide or multiply integer values.

This example will divide by 4 using the >> operator.

$firstVar = 128;

$secondVar = $firstVar >> 2;

print("$secondVar\n");

Here we

  • Assign a value of 128 to the $firstVar variable.
  • Shift the bits inside $firstVar two places to the right and
  • assign the new value to $secondVar .
  • Print the $secondVart variable.

The program produces the following output:

32

Let\'s look at the bit patterns of the variables before and after the shift operation. First, $firstVar is assigned 128 or 10000000. Then, the value in $firstVar is shifted left by two places. So the new value is 00100000 or 32, which is assigned to $secondVar.

The rightmost bit of a value is lost when the bits are shifted right. You can see this in the next example.

The next example will multiply 128 by 8.

$firstVar = 128;

$secondVar = $firstVar << 3;

print $secondVar;
The program produces the following output:
1024

The value of 1024 is beyond the bounds of the 8 bits that the other examples used. This was done to show you that the number of bits available for your use is not limited to one byte. You are really limited by however many bytes Perl uses for one scalar variable (probably 4). You\'ll need to read the Perl documentation that came with the interpreter to determine how many bytes your scalar variables use.

Comparison operators for numbers and strings

Perl has different operators (relational and equality operators)for comparing numbers and strings. They are defined as follows:

Equality Numeric String
Equal == eq
Not Equal != ne
Comparison <=> cmp
Relational Numeric String
Less than < lt
Greater than > gt
Less than or equal <= le
Greater than or equal >= ge

In controlling the logic of a conditional expression logical operators are frequently required.

In Perl, The logical AND operator is && and logical OR is ||.

For example to check if a valid number exist in a variable $var you could do:

if ( ($var ne "0") && ($var == 0))
{ # $var is a number
}

Since Perl evaluates any string to 0 if is not a number.

The numeric relational operators, listed above are used to test the relationship between two operands. You can see if one operand is equal to another, if one operand is greater than another, or if one operator is less than another.

Note It is important to realize that the equality operator is a pair of equal signs and not just one. Quite a few bugs are introduced into programs because people forget this rule and use a single equal sign when testing conditions.

Example: Using the <=> Operator

The number comparison operator is used to quickly tell the relationship between one operand and another. It is frequently used during sorting activities.

Witth the form op1 <=> op2 this operator returns 1 if op1 is greater than op2, 0 if op1 equals op2, and -1 if op1 is less than op2.

You may sometimes see the <=> operator called the spaceship operator because of the way that it looks.

In the following example op2.pl we: Set up three variables and rint the relationship of each variable to the variable

$lowVar =  8;

$midVar = 10;

$hiVar = 12;


print($lowVar <=> $midVar, "\n");

print($midVar <=> $midVar, "\n");

print($hiVar <=> $midVar, "\n");

The program produces the following output:

-1
0
1

The -1 indicates that $lowVar (8) is less than $midVar (10). The 0 indicates that $midVar is equal to itself. And the 1 indicates that $hiVar (12) is greater than $midVar (10).

The string relational operators are used to test the relationship between two operands. You can see if one operand is equal to another, if one operand is greater than another, or if one operator is less than another.

String values are compared using the ASCII values of each character in the strings. So, we\'ll only show an example of the cmp comparison operator here.

Example: Using the cmp Operator

The string comparison cmp operator acts exactly like the < => operator except that it is designed to work with string operands. The following example, cmp.pl, will compare the values of three different strings:

Set up three variables and Prints the relationship of each variable to the variable, much like the numeric example

$lowVar = "AAA";

$midVar = "BBB";

$hiVar = "ccC";


print($lowVar cmp $midVar, "\n");

print($midVar cmp $midVar, "\n");

print($hiVar cmp $midVar, "\n");

The program produces the following output:

-1
0
1
Notice that even though strings are being compared, a numeric value is returned.
You may be wondering what happens if the strings have spaces in them. Let\'s explore that for a moment. cmp2.pl: 
$firstVar = "AA";

$secondVar = " A";

print($firstVar cmp $secondVar, "\n");

The program produces the following output:

1

which means that "AA" is greater than " A" according to the criteria used by the cmp operator.

The Range Operator (..)

The range operator is used as a shorthand way to set up arrays.

When used with arrays, the range operator simplifies the process of creating arrays with contiguous sequences of numbers and letters. We\'ll start with an array of the numbers one through ten.

For example tp Create an array with ten elements that include 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10 simply write:

@array = (1..10);

You can also create an array of contiguous letters, for ecample: an array with ten elements that include A, B, C, D, E, F, G, H, I , and J. is written

@array = ("A".."J");

And, of course, you can have other things in the array definition besides the range operator.

You can create an array that includes AAA, 1, 2, 3, 4, 5, A, B, C, D, and ZZZ by the following

@array = ("AAA", 1..5, "A".."D", "ZZZ");

You can use the range operator to create a list with zero-filled numbers.

To create an array with ten elements that include the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, and 10 do:

@array = ("01".."10");

And you can use variables as operands for the range operator.

To assign a string literal to $firstVar. Create an array with ten elements that include the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, and 10:

$firstVar = "10";
@array = ("01"..$firstVar);

If you use strings of more than one character as operands, the range operator will increment the rightmost character by one and perform the appropriate carry operation when the number 9 or letter z is reached. You\'ll probably need to see some examples before this makes sense.

You\'ve already seen "A".."Z," which is pretty simple to understand. Perl counts down the alphabet until Z is reached.

Caution should be heeded however: The two ranges "A".."Z" and "a".."Z" are not identical. And the second range does not contain all lowercase letters and all uppercase letters. Instead, Perl creates an array that contains just the lowercase letters. Apparently, when Perl reaches the end of the alphabet-whether lowercase or uppercase-the incrementing stops.

What happens when a two-character string is used as an operand for the range operator?

To create an array that includes the strings aa, ab, ac, ad, ae, and af. write:

@array = ("aa" .. "af");

This behaves as you\'d expect, incrementing along the alphabet until the f letter is reached. However, if you change the first character of one of the operands, watch what happens.

If we create an array that includes the strings ay, az, ba, bb, bc, bd, be, and bf. we must write:

@array = ("ay" .. "bf");

When the second character is incremented to z, then the first character is incremented to b and the second character is set to a.

Note If the right side of the range operator is greater than the left side, an empty array is created.

The String Operators (. and x)

Perl has two different string operators-the concatenation (.) operator and the repetition (x) operator. These operators make it easy to manipulate strings in certain ways. Let\'s start with the concatenation operator. Strings can be concatenated by the . operator.

For example:

$first_name = "David";
$last_name = "Marshall";

$full_name = $first_name . " " . $last_name;

we need the " " to insert a space between the strings.

Strings can be repeated with tt x operator

For example:

$first_name = "David";

$david_cubed = $first_name x 3;

which gives "DavidDavidDavid".

String can be referenced inside strings

For example:

$first_name = "David";

$str = "My name is: $first_name";

which gives "My name is: David".

Conversion between numbers and Strings

This is a useful facility in Perl. Scalar variables are converted automatically to string and number values according to context.

Thus you can do

$x = "40";
$y = "11";

$z = $x + $y; # answer 31

$w = $x . $y; # answer "4011"

Note if a string contains any trailing non-number characters they will be ignored.

i.e. " 123.45abc" would get converted to 123.45 for numeric work.

If no number is present in a string it is converted to 0.

The chop() operator

chop() is a useful operator which takes a single argument (within parenthesis) and simply removes the last character from the string. The new string is returned (overwritten) to the input string.

Thus

chop(\'suey\') would give the result \'sue\'

Why is this useful?

Most strings input in Perl will end with a \n. If we want to string operations for output formatting and many other processed then the \n might be inappropriate. chop() can easily remove this.

Many other applications find chop() useful