Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I iterate through an array inside a Raku hash?

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.

like image 272
Digicrat Avatar asked Dec 03 '19 16:12

Digicrat


2 Answers

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.

like image 165
Scimon Proctor Avatar answered Oct 07 '22 14:10

Scimon Proctor


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.

like image 20
Digicrat Avatar answered Oct 07 '22 13:10

Digicrat