Name

Yet Another Perl 6 Operator: The Iterate Operator

Version

Maintainer: Adriano Ferreira <ferreira@cpan.org>
Date: 19 Dec 2007
Last Modified: 22 Dec 2007
Number: 13
Version: 3
Status: Draft

Body

If you are wondering how processing the lines of a file will look in Perl 6, the answer is something like this:

my $h = open '<', $filename;

for =$h {
   ...
}

(Yes, we need error handling yet. I just ommitted the details for brevity.)

Things changed. In Perl 5, we usually did:

open my $h, '<', $filename;

while ( <$h> ) {
     ...
}

The IO API is more object-oriented and the open turned into a function which returns the open IO handle if successful. The magical while (<$h>) (that was really a shortcut for while ( defined ($_ = <$h>) ) ) is gone and the for construction with the iterate '=' operator is now recommended.

The iterate operator, which is prefix '=', does not get confused with the infix operator '=' for assignment (at least, not by the compiler). They are syntactically distinct based on what the Perl parser expects at every instant: if waiting a term, '=' would be taken to be prefix; if waiting an operator, '=' would mean assignment.

The IO objects happen to implement an "Iterable" role. So they act as iterators which are objects to run through the objects of a collection, keeping their current position (or state). Their basic operation is defined by providing a sensible behavior via a 'prefix:<=>' implementation. So, iterators work as well for lists and other data structures which represent collections of items.

.say for =@list;

for =%hash.iterator -> $p {
    $p.say;
}

The examples above illustrate how invoking '=' in scalar context, produces each element of the iterated collection one at a time. If used in list context, the result of '=' turns into a lazy list, so they flatten to a list under demand. If needed, the eager list operator may be used to force immediate iteration to completion.

my $range = 1..1000; # ranges are iterators
my @list = eager =$range; # immediately computed

my $indices = 1..*;
my @list = eager =$indices; # blows up, expanding the infinite list

Notes for Perl 5 programmers: (1) The circumfix operator '< >' does not exist anymore. That syntax is now reserved as a handy synonym for the quoting construct qw and is part of a consistent set of quoting constructs for Perl 6.

< a b c >   # ('a', 'b', 'c')

(2) Also there is no fancy syntax for globs anymore. Use the builtin glob.

$Revision: 123 $