·  PERL – Syntax – Operators – Arithmetic

 

- Info:

  - This tutorial shows how to use arithmetic operators.

  - Assignment operators are just arithmetic operators which assign the result to the left operand.

 

- Numbers:

  #Test variables.---------------------------------------------------------------------------

  $x          = 10;

  $y          = 20;

 

  #Arithmetic operators.---------------------------------------------------------------------

  $negate     =    -$y;    #-20   = -20

  $add        = $x +$y;    #10+20 =  30

  $subtract   = $x -$y;    #10-20 = -10

  $multiply   = $x *$y;    #10*20 = 200

  $divide     = $x /$y;    #10/20 = 0.5    

  $exponent   = $x**$y;    #10^20 = 100000000000000000000

  $modulo     = $x %$y;    #10%20 = 0*20+10 = 10

  $increment1 =   ++$y;    #Increment $y by 1 and then store $y into increment1.

  $decrement1 =   --$y;    #Decrement $y by 1 and then store $y into decrement1.

  $increment2 =     $y++;  #Store $y into increment2 and then increment $y by 1.

  $decrement2 =     $y--;  #Store $y into decrement2 and then decrement $y by 1.

 

  #Assignement operators.--------------------------------------------------------------------

  $x += 10;                #$x = $x + 10;

  $x -= 10;                #$x = $x - 10;

  $x *= 10;                #$x = $x * 10;

  $x /= 10;                #$x = $x / 10;

  $x %= 10;                #$x = $x % 10;

  $x**= 10;                #$x = $x **10;

 

  #Display result.---------------------------------------------------------------------------

  print($add);             #Replace $add with any other variable from above to see its value.

    

- Strings:

  #Test variables.---------------------------------------------------------------------------

  $a = "First";

  $b = "Second";

 

  #Arithmetic operators.--------------------------------------------------------------------- 

  $c = $a . $b;            #FirstSecond.      Concatenate $a and $b.

  $c = $a.' and '.$b;      #First and Second. Concatenate strings.

  $c =  "$a and $b";       #First and Second. Variables are replaced with their content.

  $c = $a x 2;             #FirstFirst.       Repeat $a 2 times.

 

  #Assignement operators.--------------------------------------------------------------------

  $a.=$b;                  #FirstSecond.      Same as $a=$a.$b concatenation.

 

  #Display result.---------------------------------------------------------------------------

  print($c);               #Replace $add with any other variable from above to see its value.