Lesson 11: Numeric Operators and functions


Common numeric operators and functions

Operators summary example
+ addition of 2 numbers 2 + 2
- subtraction of 2 numbers 5 - 3
* multiplication of 2 numbers 4 * 4
/ division of left number by right number 8 / 2
% modulus, returns remainder 10 % 2
** exponent, left number raised to the right number 4 ** 2
++ increment by 1. Same as $i=$i+1 $i++
-- decrement by 1. Same as $i=$i-1 $i--
functions summary example
abs absolute value abs($i)
int get the integer portion of a number int($i)

Examples using common numeric operators and functions

Code: addition: +

1
2
3
print "sum of 2 and 3\n";
my $num = 2 + 3;
print "is $num\n";

Output:

the sum of 2 and 3
is 5

Code: subtraction: -

1
2
3
print "$num minus 2\n";
$num = $num - 2;
print "is $num\n";

Output:

5 minus 2
is 3

Code: multiplication: *

1
2
3
print "product of $num and 2\n";
$num = $num * 2;
print "is $num\n";

Output:

product of 3 and 2
is 6

Code: division: /

1
2
3
print "$num divided by 2\n";
$num = $num / 2;
print "is $num\n";

Output:

6 divided by 2
is 3

Code: modulus: %

1
2
3
print "remainder of $num divided by 2\n";
my $remainder = $num % 2;
print "is $remainder\n";

Output:

remainder of 3 divided by 2
is 1

Code: power of: **

1
2
3
print "$remainder raised to the power of 2\n";
$num = $remainder ** 2;
print "is $num\n";

Output:

1 raised to the power of 2
is 1

Code: add 1: ++

1
2
3
print "$num + 1\n";
$num++;
print "is $num\n";

Output:

1 + 1
is 2

Code: minus 1: --

1
2
3
print "$num - 1\n";
$num--;
print "is $num\n";

Output:

2 - 1
is 1

Code: absolute value: abs()

1
2
3
print "absolute value of 3 - 4.2\n";
$num = abs(3 - 4.2);
print "is $num\n";

Output:

absolute value of 3 - 4.2
is 1.2

Code: integer portion: int()

1
2
print "int portion of $num\n";
print int($num) , "\n";

Output:

int portion of 1.2
1

Exercises

  1. Write a script in which perform the above mentioned operators and functions
  2. print out each result

Print Friendly

One thought on “Lesson 11: Numeric Operators and functions

  1. Assignment operators that are handy when dealing with numbers

    • +=
    • -=

    Code:

    my $i = 2;
    $i += 2;
    ## works the same as
    ## $i = $i + 2;
    print $i , "n"
    

    Output:

    %% ./assignment_operators.pl
    4

Leave a Reply

Your email address will not be published. Required fields are marked *