Chapter 3. Numbers

This chapter steps back from the breadth of the previous chapter to focus on the idea of numbers and their representation in your programs. Perl 6 supports several types of numbers and works hard to keep them exact as long as it can.

Number Types

Not all numbers are created alike. You’ve seen whole numbers, how to do basic mathematical operations on them, and how to compare them. But whole numbers are just one of the numeric types. You can see what type a number is by calling .^name on it:

% perl6
> 137.^name
Int

That’s an Int, short for “integer”—whole numbers, positive or negative, and zero. The compiler recognizes it because it has decimal digits; it parses it and creates the object for you. But try it with a negative number:

% perl6
> -137.^name
Cannot convert string to number

The minus sign isn’t actually part of the number. It’s an operator (a unary prefix one) that negates the positive number. That means that -137 isn’t a term; it’s an expression. The .^name happens first and evaluates to Int as before. When - tries to negate the type name it realizes it can’t do that and complains. You can fix the ordering problem with parentheses—things inside parentheses happen before those outside:

% perl6
> (-137).^name

There are other types of numbers, some of which are shown in Table 3-1.

Table 3-1. Examples of different number types
ValueClassDescription
137IntPositive integer (whole number)
-17IntNegative integer (whole number)
3.1415926RatFractional number
6.026e34NumScientific ...

Get Learning Perl 6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.