Raku Books / Perl 6 at a Glance / New Concepts / Channels
Read and write
In Perl 6, there is a predefined class Channel, which
includes, among the others, the send and the
receive methods. Here is the simplest example, where an
integer number first is being sent to the channel $c and is
then immediately read from it.
CodeBlockPlaceholder1raku-async my $c = Channel.new; $c.send(42); say $c.receive; # 42 CodeBlockPlaceholder2
A channel can be passed to a sub as any other variable. Should you do that, you will be able to read from that channel in the sub.
my $ch = Channel.new;
$ch.send(2017);
func($ch);
sub func($ch) {
say $ch.receive; # 2017
}🧵 This program uses concurrency (promises, threads). The in-browser engine (Raku.js) is single-threaded and can’t run it yet — try it on your own computer.
CodeBlockPlaceholder4raku-async my $channel = Channel.new;
A few even numbers are sent to the channel.
for <1 3 5 7 9> { $channel.send($_); }
Now, we read the numbers until the channel has them.
“while @a -> $x” creates a loop with the $x as a loop variable.
while $channel.poll -> $x { say $x; }
After the last available number, Nil is returned.
$channel.poll.say; # Nil CodeBlockPlaceholder5raku-static $channel.close; while $channel.receive -> $x { say $x; } CodeBlockPlaceholder6raku-static $channel.close; try { while $channel.receive -> $x { say $x; } } ```
Here, closing a channel is a required to quit after the last data piece from the channel arrives.
Course navigation
← Channels | The list method →