Last Updated:

Arithmetic operations in Perl

Arithmetic operations in Perl

The programming language, providing the ability to define various types of data, must provide their processing, because its main goal is to implement data processing algorithms. Valid actions on data are performed using a set of operations defined in the programming language. An operation is the execution of a specific action on operands, the result of which is a new value. From the point of view of mathematics, an operation can be considered as a kind of function that calculates a new value from given variables (operands).

Everyone knows from school four basic arithmetic operations performed on numbers: addition (+), subtraction (-), multiplication (*) and division (/). We always perform these actions (operations) on two numbers (operands), resulting in a new number. The programming language defines not only arithmetic operations on numeric data, but also operations applicable to other valid data types. These can be operations on strings, arrays, etc. The only important thing is that there is an operation defined by its sign, and there are operands involved in it, collectively allowing you to get (calculate) a new value that can belong to one of the valid types. Literals, variables, and expressions, which are combinations of basic operations, can be used as operands. The general syntax of the operation can be represented as follows:

operand op_sign operand 

For some operations, one of the operands may be omitted. In this case, the operation is called single-seat or unary, for example, calculating the opposite sign value of the operand - $t. If two operands are involved in the operation, the operation is called double or binary. Virtually all valid operations are unary or binary, but some modern programming languages define an one-to-one conditional ternary operation that requires three operands. The meaning of this operation is the second or third operand, depending on the truth and falsity of the first:

operand 1? operand 2: operand 3 

Syntactically, an expression is represented as a sequence of operands and signs of operations, which is usually interpreted from left to right taking into account the order of precedence of operations, that is, rules that determine in which sequence the operations present in the expression are performed. Parentheses are used to change the order of execution. The result of processing an expression by the interpreter is some calculated value that is used in other language constructs that implement a data processing algorithm.

This chapter details perl operations and how to use them when constructing expressions. Several dozen operations are defined in the Perl language. They can be grouped by the type of actions performed (arithmetic, bitwise, logical, relationships, assignments), what data they affect (string, list, file), and not related to any of the listed types (comma, reference, dereferencing and selection operations). Following this classification of Perl operations, we will introduce them to our readers. Some operations will be analyzed in detail, others we will only give a general idea, referring a more detailed description in other chapters of our book.

All arithmetic operations can be divided into three groups: binary, unary and increase/decrease. Their main purpose is to perform certain calculations on numerical data, but in all arithmetic operations, string data can also act as operands, and it is not necessary that they be converted into numerical data.

Binary arithmetic operations

Binary arithmetic operations are four known arithmetic operations: addition (+), subtraction (-), multiplication (*), and division (/), to which two more are added: the remainder of dividing two integers (%) and exponentiation (**). Applied to numeric or string data that contains the correct literals of decimal numbers, they perform the appropriate arithmetic (Example 4.1).

3.14 + 123; # Result: 126.14
"3.14" + "123"; # Result: 126.14
"3.14" + 123; # Result: 126.14
"3.14" * 10; # Result: 31.4
300-200; # Result: 100
300 / 200; # Result: 1.5
3% 2; # Result: 1
2**3;. # Result: 8
(-2)**3; # Result: -8 '
2**(-3); # Result: 0.125
2.5**1.5; # Result: -23.95284707521047

As you can see, binary arithmetic operations "work" exactly as we are used to using them in ordinary arithmetic calculations in our everyday life.

Remark
If the operand in the operation of obtaining the residue from the division of integers (%) is a real number with a fractional part, then it is transformed to the whole by simply discarding the fractional part, after which the operation is performed on the integers
.

Remark
You can't raise a negative number not to an integer. If this happens, the interpreter does not give any error, but the result of such an operation is zero: (-2.5) ** (1.3) = o
.

As operands of binary arithmetic operations, you can use strings that do not contain the correct numeric literals. In this case, the interpreter will try to extract a number from the contents of the string, starting with the first character, and use it as the corresponding operand of the specified operation. If the correct numeric literal cannot be selected, the operand assumes a value equal to o. Similar situations are demonstrated in Example 4.2.

"3fl4" + "12-30"; # Result: 15 ("3" + "12")
"a!20" + "12-30"; # Result: 12 ("0" + "12")
"a!20" + "-0012-30"; # Result: -12 ("0" + "-12")

Note
If you set the display mode of the interpreter warning messages (key – w), then when you try to use strings that do not contain the correct numeric literals in binary arithmetic operations, a message of the form will be displayed:

Argument "al20" isn't numeric in add at D:\EXAMPLE1.PL line 2.

Binary arithmetic operations are performed in a scalar context. This means that the operands must be scalar variables, and the variables of scalar and hash array arrays accept values equal to the number of elements of the scalar arrays or the number of records used in the hash table according to the requirements of the scalar context (Example 4.3).

@m = (2, 4, 6, 8, 10);
%ml = (1 › "a", 2 › "b"};
$n = 100;
$n + @m; # Result: 105 (100 + 5)
@m + %ml; # Result: 7 (5+2)

Remark
In a scalar context, a hash array takes a string value consisting of the number of used sections of records in a hash table and the number of selected areas of records separated by the "/" character (see Chapter 3). The number used in arithmetic operations is obtained by isolating a numeric literal from this row, which corresponds to the number of records used in the hash table
.

Unary arithmetic operations

In Perl, there are only two unary arithmetic operations (+) and (-). The unary plus + applied to data of any type represented by literals or its variables has no semantic effect. It is useful before an expression in parentheses immediately after the function name if you want to visually emphasize the fact that the function is actually a list operation.

The unary minus (-) performs the arithmetic negation of the numerical operand. This means that if the number was negative, then it will become positive, and vice versa. If the operand is an identifier, the result of this operation is a string consisting of the "-" character followed by the identifier. If the operand is a string that begins with a minus or plus character, the result is also a string in which minus is replaced by plus and vice versa. For lines that do not begin with a plus or minus, the unary minus operation adds it to the first character in the string. All of these cases of the use of the unary minus are shown in Example 4.4.

-'12.09'; # Result: -12.09
-(-12.09);# Result: 12.09
-id; # Result: '-id'
-'+id"; # Result: '-id'
-"-id"; # Result: "+id"
-'a!20'; # Result: '-a!20'

Increase and decrease operations

The operations of increasing (++) and decreasing (--) are similar to the same operations in C. (The authors of the Perl language do not hide the fact that they borrowed much from this language.) The result of these operations depends on whether they are before (prefix form) or after a variable (postfix form). When using a prefix form, they increase or decrease the numeric value of the variable by one, respectively, until the value is returned. The postfix form of these operations changes the numeric value of the variable after they return the value. The effect of these operations on numeric variables is illustrated by Example 4.5 (the operators of the program fragment are executed sequentially).

$n = 10.7; # Initial value
$infl = -$n; # Result: $infl = 9.7 and $n=9.7
$inf2 = ++$n; # Result: $inf2 = 10.7 and $n = 10.7
$postl = $n--; # Result: $postl = 10.7 but $n= 9.7
$post2 = $n++; # Result: $post2 = 9.7 but $n= 10.7

An increment operation (prefix and postfix) applied to a variable that contains a string of a certain kind is somewhat unusual. If the string consists only of Latin letters, then the return value of the increment operation will be a string in which the last letter is replaced by the next letter of the alphabet in order, with the lowercase one replaced by lowercase and uppercase by uppercase. If a string ends with consecutive letters "z" or "z", they are all replaced with "a" or "A", respectively, and the letter in front of them in the line is replaced with the next letter of the alphabet. If the entire string consists of the letters "z" and "z", then in addition to replacing these letters in accordance with the previous rule, a lowercase or uppercase letter "a" is added before them, depending on whether the lowercase or uppercase letter "z" was the first in the line.

Similar actions are performed if the line ends with a sequence of digits: the last digit is incremented by one. If the string ends with consecutive digits 9, then all of them are replaced by o, and the adjacent character is "increased" by one: for a letter, it goes to the next in alphabetical order, and for a number to the next in order digit. If the sequence consists entirely of nines, then all of them are replaced by zeros, before which one is added. The prefix and postfix forms of the operation act as usual. Several illustrations of these operations are presented in Example 4.6.

$s = "abc"
$sl = ++$s; # Result: $sl = "abd"
$s = "abC";
$sl = ++$s; # Result: $sl = "abD"
$s = "abz";
$sl = ++$s; # Result: $sl = "asa"
$s = "abzZz";
$sl = ++$s; # Result: $sl = "acaAa"
$s = "ab09";
$sl = ++$s; # Result: $sl = "abl0"
$s = "99";.
$sl = ++$s; # Result: $sl = "100"

Remark
The reduction operation (
--) works with special strings in the same way as with regular strings. An attempt is made to select a numeric literal starting with the first character. If this is possible, the numeric value of the string is equated to the allocated numeric literal, if not, its value is considered equal to 0. A reduction operation is then applied to the calculated numeric value of the string.