Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 43 ยท Scalars and Operators

Operators and Numbers

Learn Perl operators: arithmetic, == versus eq, <=> versus cmp, logical and defined-or, ranges, string increment, and how numbers are written and printed.

Perl has an operator for almost everything, and it has one rule that surprises newcomers more than any other: the operator decides how a value is read, not the variable. A scalar holding "10" is a number when you add to it and a string when you glue text to it. That is why Perl has two complete sets of comparison operators, one for numbers and one for strings.

This lesson tours the operators you will use every day: arithmetic, the paired comparison operators, the logical operators (including the very useful defined-or), ranges and the "magic" string increment. It also covers how numbers are written in source code and how Perl prints them. If you have not met scalars yet, read Scalar Variables first.

Perl is not installed on this site, so the Perl listings below are read-only. The TryIt blocks use Python as an honest stand-in: they reproduce what the Perl operators do, so you can watch the rules play out. The Perl outputs shown in the text come from real runs of Perl 5.42.

Arithmetic

The usual operators work as you expect. ** is exponentiation, % is the remainder, and / always does real division (there is no integer division operator).

PERL
use v5.36;

say 7 + 3;       # 10
say 7 - 3;       # 4
say 7 * 3;       # 21
say 7 / 2;       # 3.5
say 7 % 3;       # 1
say 2 ** 10;     # 1024
say int(7 / 2);  # 3 (int truncates toward zero)
say int(-7 / 2); # -3

Two details are worth remembering. First, % takes the sign of its right operand, so -7 % 3 is 2 and 7 % -3 is -2. That is handy for wrapping an index around an array: $i % @items is never negative when the divisor is positive. Second, int chops the decimals; it does not round. For rounding, use sprintf("%.0f", $x) (see Working with Strings).

Perl also has assignment forms of every operator: +=, -=, *=, /=, **=, %=, .= (append) and x= (repeat). ++ and -- add or subtract one, before or after the value is used.

PERL
my $x = 5;
$x += 3;    # 8
$x *= 2;    # 16
$x **= 2;   # 256
$x %= 7;    # 4

my $i = 5;
my $j = 5;
say $i++ + ++$j;   # 5 + 6 = 11

Floating-point numbers

Perl stores most non-integers as ordinary double-precision floats, so the classic surprise applies here as in most languages:

PERL
say 0.1 + 0.2;                          # 0.3
say 0.1 + 0.2 == 0.3 ? "equal" : "not equal";   # not equal
say 10 / 3;                             # 3.33333333333333

Perl prints floats with about 15 significant digits, which hides the tiny error in 0.1 + 0.2. The comparison still sees the true stored values and says they differ. When you compare computed decimals, check that the difference is small instead: abs($a - $b) < 1e-9.

Strings and numbers: the operator decides

Arithmetic operators turn their operands into numbers. If a string starts with something that looks like a number, Perl uses that part and ignores the rest. A string with no leading number counts as 0. Under use warnings (see use strict and use warnings) Perl tells you when it has to guess.

PERL
say "10" + "20";        # 30
say "3 apples" + 4;     # 7  (warning: Argument "3 apples" isn't numeric)
say "abc" + 1;          # 1  (warning, "abc" counts as 0)

String operators do the opposite and turn their operands into text. The dot . joins strings and x repeats them:

PERL
say "ab" . "cd";   # abcd
say "ab" x 3;      # ababab
say "-" x 10;      # ----------
my @row = (1) x 3; # a list repetition: (1, 1, 1)

x has a second meaning: when the left side is a list in parentheses, it repeats the list, not a string. That is how (1) x 3 produces three ones.

Two families of comparison

Every comparison exists twice. The numeric version uses symbols, the string version uses letters. Picking the wrong one is the most common beginner bug in Perl.

Numbers use symbols

== != < > <= >= Compare the numeric values.
<=> Returns -1, 0 or 1.

10 == 10.0 is true.

1 / 3
PERL
say 10 == 10.0 ? "yes" : "no";     # yes: the numbers are equal
say "10" eq "10.0" ? "yes" : "no"; # no: the texts differ
say "apple" lt "banana" ? "lt" : "ge";   # lt
say 2 <=> 10;       # -1
say "2" cmp "10";   # 1  ("2" sorts after "1")
say 5 <=> 5;        # 0

<=> (nicknamed the spaceship) and cmp return -1, 0 or 1. You rarely print them; their job is to feed sort. This is the reason sort without a block sorts as text:

PERL
say join ",", sort (10, 9, 100, 1);                # 1,10,100,9
say join ",", sort { $a <=> $b } (10, 9, 100, 1);  # 1,9,10,100

The default is a string sort, so "100" comes before "9". Add a block with <=> to sort numerically. We return to sorting in List Functions and Sorting.

Python Numeric versus string comparison (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

== on two strings never raises an error. With use warnings Perl prints a "isn't numeric" message, but without it "abc" == "xyz" is simply true (both become 0). Always use eq for text.

Logical operators and defined-or

Perl has two spellings of the logical operators. The symbol forms &&, || and ! bind tightly. The word forms and, or and not bind very loosely, which makes them good for flow control such as open(...) or die, and a poor choice inside an expression with an assignment.

What makes Perl's operators special is what they return. || does not return true or false; it returns the first operand that is true, or the last operand. && returns the first false operand, or the last one. This enables the default-value idiom:

PERL
my $name;
my $label = $name || "guest";    # guest

There is a catch. || treats 0 and the empty string as false, so a legitimate zero gets replaced:

PERL
my $count = 0;
say $count || "fallback";   # fallback  (not what you wanted)
say $count // "fallback";   # 0

The defined-or operator // (Perl 5.10 and later) only falls back when the left side is undef. Use it whenever 0 or "" are valid values. There is also //=, which assigns only if the variable is still undefined:

PERL
my %opts;
$opts{retries} //= 3;      # sets 3 the first time
$opts{retries} //= 99;     # leaves 3 alone

The full list of false values is covered in Conditionals.

Ranges and magic increment

The range operator .. builds a list of consecutive values. It works with numbers and, thanks to Perl's string rules, with letters:

PERL
my @nums = (1..5);               # 1 2 3 4 5
say join ",", ('a'..'e');        # a,b,c,d,e
say join ",", ('aa'..'ad');      # aa,ab,ac,ad

Behind that is the magic string increment. If a variable holds a string made only of letters and digits (a pattern such as ^[a-zA-Z]*[0-9]*$), ++ steps it forward like an odometer, carrying over to the left:

PERL
my $v = "aa9";  $v++;   # ab0
my $w = "Az";   $w++;   # Ba
my $q = "zz";   $q++;   # aaa
my $n = "a9";   $n++;   # b0

It only works for ++; -- always converts to a number. Magic increment is great for generating labels like A1, A2, ... Z9, AA0, and a trap when a string like "abc" was supposed to be numeric.

Python Magic increment (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing numbers

Perl accepts several literal formats, and underscores make big numbers readable:

PERL
say 1_000_000;   # 1000000
say 0xff;        # 255   (hexadecimal)
say 0b1010;      # 10    (binary)
say 0o17;        # 15    (octal, the 0o prefix needs Perl 5.34 or later)
say 017;         # 15    (a leading 0 also means octal)
say 1.5e3;       # 1500

Watch the leading zero: 017 is octal 15, not seventeen. When Perl prints a number it uses the shortest sensible form, and very large or very small values switch to scientific notation:

PERL
say 1e21;       # 1e+21
say 1 / 7;      # 0.142857142857143
say 2 ** 53;    # 9.00719925474099e+15

Integers that fit in the machine word (64 bits on most systems) stay exact. Results from ** and big arithmetic can become floats, which is why 2 ** 53 printed in scientific notation above. When you need an exact large integer, use use bigint; or the Math::BigInt module, or sprintf("%d", ...) for a plain integer format.

Bitwise operators

Bitwise operators work on the individual bits of integers. They are handy for flags, masks and low-level protocols.

Operator Name Example Result
& AND 0b1100 & 0b1010 0b1000
| OR 0b1100 | 0b1010 0b1110
^ XOR 0b1100 ^ 0b1010 0b0110
~ NOT (flip every bit) ~0b1100 & 0b1111 0b0011
<< shift left 1 << 4 16
>> shift right 256 >> 2 64

~ flips all bits of a 64-bit integer, so mask the result (& 0b1111) when you only care about a few bits. A common use is a set of option flags:

PERL
use v5.36;
my ($READ, $WRITE) = (1, 2);
my $flags = 0;
$flags |= $WRITE;                       # turn a flag on
say(($flags & $WRITE) ? "can write" : "read-only");   # can write
$flags &= ~$WRITE;                      # turn it off again

Each has an assignment form: &=, |=, ^=, <<= and >>=. Old Perl treated &, | and ^ as string operators when both sides were strings. With use v5.28 or later (which enables the bitwise feature) they are always numeric, and the separate &., |. and ^. operators do the string version.

Precedence and associativity

When an expression has several operators, precedence decides which binds first and associativity decides the order among equals. From tightest to loosest, the ones you meet most often are:

  1. ++ --
  2. ** (right associative)
  3. ! ~ unary -
  4. =~ !~
  5. * / % x
  6. + - .
  7. << >>
  8. < > <= >= lt gt le ge
  9. == != <=> eq ne cmp
  10. &, then | ^
  11. &&, then || //
  12. .., then ? :
  13. = += .= and friends (right associative)
  14. not, then and, then or xor
PERL
say 2 ** 3 ** 2;    # 512, because ** groups from the right: 2 ** 9
say -2 ** 2;        # -4, because ** binds tighter than unary minus
say 1 < 2 < 3 ? "chain" : "no";   # chain (comparison chaining, Perl 5.32+)

When in doubt, add parentheses: they cost nothing and tell the next reader what you meant.

Operator kinds

Perl's manual groups operators by arity (how many operands) and fixity (where the operator sits):

  • Unary: one operand, such as !$x or -$n. Binary: two, such as $a + $b. The ternary ? : takes three.
  • Nullary terms take none, such as time or wantarray. List operators such as print or push take a whole list on their right.
  • Prefix operators come before the operand (!), postfix after it ($i++), infix between operands (+). Brackets and quotes are circumfix ((...), [...], "..."), and subscripts like $a[0] or $h{k} are postcircumfix.

More on ++ and --

++ and -- come in prefix and postfix forms. The prefix form changes the value first and returns the new value; the postfix form returns the old value:

PERL
my $x = 10;
my $y = $x++ + ++$x;   # 10 + 12
say "$x $y";           # 12 22

Only ++ is magical on strings: "az"++ gives "ba", "Zz"++ gives "AAa" and "a9"++ gives "b0". -- on a string is plain numeric arithmetic, so "aa"-- becomes -1.

Remainder with negative numbers

The sign of % follows the right operand: 7 % 3 is 1, -7 % 3 is 2 and 7 % -3 is -2.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "10" == 10.0 return in Perl?

    The == operator converts both operands to numbers, so the string "10" and the float 10.0 are both 10.
  2. 2. Which expression gives the default "guest" only when $name is undef (so 0 and "" are kept)?

    The defined-or operator // only falls back for undef. || also replaces 0 and the empty string.
  3. 3. What does sort (10, 9, 100, 1) return without a block?

    The default sort compares as strings, so "100" sorts before "9". Use sort { $a <=> $b } for numeric order.
  4. 4. What is the value of $v after my $v = "Az"; $v++;?

    Magic string increment steps the last letter (z wraps to a) and carries one position left, turning A into B.
  5. 5. Which operator compares two strings and returns -1, 0 or 1?

    cmp is the string version of the spaceship operator. <=> does the same for numbers, while eq returns only true or false.

Summary

  • Operators decide how a value is read: + and == use numbers, . and eq use text.
  • Use ==, <=> for numbers and eq, cmp for strings; the default sort is a string sort.
  • || and && return one of their operands; // falls back only for undef, so 0 survives.
  • .. builds ranges of numbers or letters, and ++ on a string steps it like an odometer.
  • Write big numbers with underscores, remember that a leading 0 means octal, and compare floats with a tolerance.

Next: Context: Scalar vs List