Name

Yet Another Perl 6 Operator: Range Operators

Version

Maintainer: Adriano Ferreira <ferreira@cpan.org>
Date: 17 Dec 2007
Last Modified: 18 Dec 2007
Number: 9
Version: 3
Status: Draft

Body

In Perl 6, you may construct ranges with expressions like

$min  ..  $max
$min ^..  $max
$min  ..^ $max
$min ^..^ $max

and even

^$limit

These operators are Range object constructors, specified by their endpoints. These endpoints are excluded if there is ^ in the corresponding side of the range operator. Thus,

 0  ..^ 4     # equivalent to  0, 1, 2, 3
 1  ..  4     # equivalent to  1, 2, 3, 4
 1 ^..  3     # equivalent to  2, 3
-2 ^..^ 2     # equivalent to -1, 0, 1

Range objects are lazy iterators. So they can represent efficiently very large or even infinite lists.

Reversed ranges cannot be constructed by just exchanging the endpoints. So 2..1 is always a null range. The solution is to use one of the expressions below.

2 .. 1 :by(-1)
reverse 1 .. 2

where reverse has the benefit of working even for alphabetic ranges.

To build possibly unbounded ranges, * may occur in any of the endpoints.

0..*     # 0 .. +Inf
'a'..*   # 'a' .. 'zzzzz...'
*..0     # -Inf .. 0
1.2.3..* # Any version higher than 1.2.3
May..*   # May through December

These examples also show that to build ranges it is enough to have endpoints whose types are Ordered, which basically means there exist sensible comparisons among its instances. To know more about Perl 6 Ranges, their methods and expected semantics, read section "Range Semantics" from Synopsis 03 .

The upto operator (unary '^') is really a shortcut to generate a range from 0 up to one less than its argument.

^$limit  #   0 ..^ $limit

which is handy for cases like this:

.say for ^4     # 0, 1, 2, 3

If applied to a type name, ^Moose is short for Moose.HOW, taking from its argument to the metaclass instance instead. This behavior is akin to "what's this thing's domain" which correlates abstractly to how ^$n works.

The operator '..' was relieved of the Perl 5 semantics of flip-flop operator, whose Perl 6 counterpart will be seen in yet another article of this series.

As a curiosity, notice that to construct ranges within Perl 6 regular expressions, the '-' was consistently replaced by '..'.

tr/a..z/A..Z/;

$Revision: 94 $