← Back to Perl Course | Chapter 2: Variables | Lesson 2 of 7

Numbers and operators

Perl has separate operators for numbers and for strings, and it picks the conversion for you.

In this page:

  1. Numbers and operators

Numbers and operators

Arithmetic uses + - * / % and ** for exponent, and the increment operators ++ and --. The dot operator . joins strings and x repeats them, while == and eq compare numbers and strings respectively. Perl converts automatically, so "10" + 5 is 15 and 10 . 5 is "105".

Note: Division with / is not integer division; use int() to truncate the result.

Example: Numbers and operators

perl
use strict;
use warnings;

my ($a1, $b1) = (7, 2);
print "sum: ", $a1 + $b1, "\n";
print "division: ", $a1 / $b1, "\n";
print "integer part: ", int($a1 / $b1), "\n";
print "modulus: ", $a1 % $b1, "\n";
print "power: ", $a1 ** $b1, "\n";
print "join: ", $a1 . $b1, "\n";
print "repeat: ", "ab" x 3, "\n";
my $count = 5;
$count++;
$count += 10;
print "count: $count\n";
print "10 == 10.0 is ", (10 == 10.0 ? "true" : "false"), "\n";
print "'10' eq '10.0' is ", ('10' eq '10.0' ? "true" : "false"), "\n";

# Output:
# sum: 9
# division: 3.5
# integer part: 3
# modulus: 1
# power: 49
# join: 72
# repeat: ababab
# count: 16
# 10 == 10.0 is true
# '10' eq '10.0' is false
Common Mistakes
  1. Using == to compare strings
  2. Expecting 7 / 2 to give 3
  3. Using + to join strings instead of .
Chapter Summary
  • Numeric operators are + - * / % **
  • . joins and x repeats strings
  • == compares numbers and eq compares strings
  • / gives a floating-point result
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.