Is it possible to avoid creating temporary scalars when returning multiple arrays from a function:
use v6;
sub func() {
my @a = 1..3;
my @b = 5..10;
return @a, @b;
}
my ($x, $y) = func();
my @x := $x;
my @y := $y;
say "x: ", @x; # OUTPUT: x: [1 2 3]
say "y: ", @y; # OUTPUT: y: [5 6 7 8 9 10]
I would like to avoid creating the temporary variables $x
and $y
.
Note: It is not possible to replace the function call with
my (@x, @y) = func()
since assignment of a list to an Array
is eager and therefore both the returned arrays end up in @x
.
Not either of:
my ($x, $y) = func();
my (@x, @y) = func();
But instead either of:
my (@x, @y) := func();
my ($x, $y) := func();
Use @
to signal to P6 that, when it needs to distinguish whether something is singular -- "a single array" -- or plural -- "items contained in a single array" -- it should be treated as plural.
Use $
to signal the other way around -- it should be treated as singular.
You can always later explicitly reverse this by doing $@x
-- to signal P6 should use the singular perspective for something you originally declared as plural -- or @$x
to signal reversing the other way around.
For an analogy, think of a cake cut into several pieces. Is it a single thing or a bunch of pieces? Note also that @
caches indexing of the pieces whereas $
just remembers that it's a cake. For large lists of things this can make a big difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With