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

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);
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);

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).

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:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s