๐Ÿ“˜ Transfer non-scalar objects through Perl 6 channels

๐Ÿ“˜ Transfer non-scalar objects through Raku channels

N. B. Perl 6 has been renamed to Raku. Click to read more.


Channels may also transfer both arrays and hashes and do it as easily as they work with scalars. Unlike Perl 5, an array will not be unfolded to a list of scalars but will be passed as a single unit. Thus, you may write the following code.

my $c = Channel.new;
my @a = (2, 4, 6, 8);
$c.send(@a); 
say $c.receive; # [2 4 6 8]

The @a array is sent to the channel as a whole and later is consumed as a whole with a single receive call.

Whatโ€™s more, if you save the received value into a scalar variable, that variable will contain an array.

my $x = $c.receive;
say $x.WHAT; # (Array)

The same discussions apply to hashes.

my $c = Channel.new;
my %h = (alpha => 1, beta => 2);
$c.send(%h);ย 

say $c.receive; # {alpha => 1, beta => 2}

Instead of calling the list method, you can use the channel in the list context (but do not forget to close it first).

$c.close;
my @v = @$c;
say @v; # [{alpha => 1, beta => 2}]

Note that if you send a list, you will receive it as a list element of the @v array.

Here is another example of โ€œdereferencingโ€ a channel:

$c.close;
for @$c -> $x {
ย ย ย  say $x;
} # {alpha => 1, beta => 2}

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code