Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one assign an item contextualized Array to a positional?

Tags:

raku

rakudo

In Rakudo Perl 6 item or $ can be used to evaluate an expression in item context. See https://docs.perl6.org/routine/item

I am using a library that returns an item contextualized Array. What is the proper way to remove the contextualization so it may be assigned to a @ variable?

For example:

my @a = $[<a b c>];
dd @a; # Outputs: Array @a = [["a", "b", "c"],]
like image 480
J Hall Avatar asked Dec 11 '25 17:12

J Hall


2 Answers

Perl being Perl, there's more than one way to do it, such as

dd my @ = @$[<a b c>];     # via original array, equivalent to .list
dd my @ = $[<a b c>][];    # via original array, using zen slicing
dd my @ = |$[<a b c>];     # via intermediate Slip, equivalent to .Slip
dd my @ = $[<a b c>].flat; # via intermediate flattening Seq

The most clear solution is probably enforcing list context via @ or .list, and I'd avoid the .flat call because it has slightly different semantic connotations.

Just as a reminder, note that list assignment is copying, but if you used one of the approaches that just pull out the original array from its scalar container, you could also use binding. However, in that case you wouldn't even need to manually decontainerize as

dd my @ := $[<a b c>];

also gets you back your array as something list-y.

like image 54
Christoph Avatar answered Dec 14 '25 05:12

Christoph


Flatten it:

my @a = $[<a b c>].flat;

dd @a; # Array @a = ["a", "b", "c"]
like image 42
Christopher Bottoms Avatar answered Dec 14 '25 06:12

Christopher Bottoms