[% setvar title Coroutines for Perl %]

This file is part of the Perl 6 Archive

Note: these documents may be out of date. Do not use as reference!

To see what is currently happening visit http://www.perl6.org/


Coroutines for Perl


  Maintainer: Tom Scola <tscola@inch.com>
  Date: 4 Aug 2000
  Mailing List: perl6-internals@perl.org
  Number: 27
  Version: 1
  Status: Developing


Two motavations for the development of Perl 6 are to bring threading and event-based programming to the core language. Coroutines can be implemented in either a threaded or an event-based manner, are at a much higher level conceptually, and are much easier to program than either of those methods. As implemented in perl, coroutines use programming methods that most perl programmers are already familiar with, making the transition to them simple and natural.


This proposal introduces a new keyword to perl, "co", as a complement to "sub". A subroutine is defined thusly:

  co foo { ... }

Coroutines can also be closures:

  my $x = co { ... }

Unlike coroutines as defined by Knuth, and implemented in laguages such as Simula or Python, perl does not have an explicit "resume" call for invoking coroutines. Instead, perl uses a mechanism that perl programmers are already familiar with: pipes. Note that these are intra-process pipes, and would be implemented differently than kernel pipes.

Coroutines are identified by a prefixed vertical bar. To invoke a coroutine, you write data to or read data from it.

   $y = <|foo>;

   print |$x "hello, world\n";

Inside a coroutine, the meanings of "<>" and the default file descriptor for print, printf, etc. are overloaded.

Coroutines and pipelines would effectively turn Perl into a dataflow programming language, providing yet another paradigm for Perl to encompass.


Coroutines can be implemented in their traditional manner, using context switching, or as threads, but would hide the mundane details of threads from the programmer. They would be more suited for producer/consumer type problems rather than massively parallel compuations, but I doubt there is much call for the latter to be implemented in perl.