This seems like a simple question, but Perl6/Raku isn't behaving as I'd expect. I'm trying to create a reference to an array within a hash, but am not getting the expected behavior. In Perl5, the answer would involve accessing the array by reference, but I don't see equivalent syntax for Perl6/Raku.
my $jsonstr = q:to/END/;
{
"arr" : [
"alpha","beta","delta","gamma"
]
}
END
my %json = from-json $jsonstr;
my @arr = %json{'arr'};
say "Arr length is " ~ @arr.elems; # Expect 4, get 1
say "Orig length is " ~ %json{'arr'}.elems; # Get expected value of 4
say "Arr[0] is " ~@arr[0].^name ~ " of length " ~ @arr[0].elems; # First index is array
say %json{'arr'}[0]; # Indexing into array in original location works as expected
say @arr[0][0]; # But when assigned, it needs an extra index
my @arr2 = @arr[0]; # Same issue in re-assignment here
say "Arr2[0]: " ~ @arr2[0] ~ ", length of " ~ @arr2.elems;
How do I get a new @arr variable to reference the nested array without this confusing extra [0] index layer? Is this a bug, or am I missing something in my understanding of Raku's Array/ref handling? Thanks.
When you assign the value in the key arr
to the Array @arr
it takes the value in %json{'arr'}
which is the Array Object ["alpha","beta","delta","gamma"]
and puts it into @arr
so you get an Array of Array's with 1 item.
You've got a few options :
You can bind @arr
to %json{"arr"}
with my @arr := %json{"arr"}
Or you can pass the %json{"arr"}
to a list with my (@arr) = %json{"arr"}
You have to remember in Raku Array's are Objects.
As usual, after writing+posting my question, I answered my own question.
my @arr = %json{'arr'}.Array;
I don't quite understand why this is necessary, but it gives the desired behavior.
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