Numbers

Literals

Perl has one numeric type behind the scenes: a scalar that holds an integer or a floating point value, whichever fits. You never declare which one you mean.

Decimal, hexadecimal, binary and octal forms are all available, and underscores may group long digits for readability:

my $decimal = 1_000_000; my $hex = 0xff; # 255 my $binary = 0b1010; # 10 my $float = 3.14; print "$hex $binary\n"; # prints 255 10

perl demo.pl

255 10

Arithmetic

The five familiar operators plus one for exponentiation cover almost everything. Division always produces a float, so use int when you want the whole part.

print 7 + 3, " "; # 10 print 7 - 3, " "; # 4 print 7 * 3, " "; # 21 print 7 / 2, " "; # 3.5 print 7 % 2, " "; # 1 print 2 ** 10, "\n"; # 1024

perl demo.pl

10 4 21 3.5 1 1024

The modulo operator follows the sign of the right operand, so -7 % 3 is 2, not -1. Test it in the debugger when a result surprises you.

int and sprintf

int truncates toward zero, which is not the same as rounding. For real rounding add half a unit first, or let sprintf do the formatting: it understands decimal places and thousands of variants.

my $x = 3.7; print int $x, "\n"; # 3 print sprintf "%.2f\n", $x; # 3.70 print sprintf "%05d\n", 42; # 00042

perl demo.pl

3
3.70
00042

Inside a string, the same formats work through printf, which prints instead of returning the result. Use printf when the formatted text goes straight to the screen.

printf "%s has %d items\n", "cart", 3;

perl demo.pl

cart has 3 items

Numeric comparison

Perl keeps two families of comparison operators: numeric ones and string ones. Comparing numbers with the string operators is a classic bug, because 10 sorts before 9 as text.

print "equal\n" if 10 == 10; print "smaller\n" if 9 < 10; print "different\n" if 9 != 10;

perl demo.pl

equal
smaller
different

The complete set is ==, !=, <, >, <=, <=> for numbers and eq, ne, lt, gt, le, cmp for strings. The last one in each list returns -1, 0 or 1, which is exactly what sort wants.

Next: Strings

Article author: Arthur Isaev