Array stays array when looped through `for`

  • A+
Category:Languages

I'm looping through the depends array from a META6.json. I've loaded into a Hash using JSON::Fast. When I'm looping through it using a for loop, however, it only goes through the loop once, and the item is the same array:

use JSON::Fast; my %meta = from-json(slurp("META6.json"));  for %meta<depends> -> $dependency {     dd $dependency; } 

This piece of code returns

Array $dependency = $["Config::Parser::toml:ver<1.0.1+>", "Config:api<1>:ver<1.3.5+>", "Dist::Helper:ver<0.21.0+>", "Hash::Merge", "Terminal::Getpass:ver<0.0.5+>", "zef"] 

I'm expecting it to loop through the %meta<depends> 6 times, which each iteration holding a different element from that array.

For good measure, this is the output of dd %meta<depends> from the example:

Array %meta = $["Config::Parser::toml:ver<1.0.1+>", "Config:api<1>:ver<1.3.5+>", "Dist::Helper:ver<0.21.0+>", "Hash::Merge", "Terminal::Getpass:ver<0.0.5+>", "zef"] 

Why is the loop not looping the way I expected?

EDIT: I'm using the latest Rakudo Star:

This is Rakudo Star version 2018.04.1 built on MoarVM version 2018.04.1 implementing Perl 6.c. 

 


This is a pitfall. Essentially this is like:

my $var = ['a', 'b', 'c']; for $var -> $v {     dd $v; } 

Which gives you: $["a", "b", "c"]

If you iterate an array with @ sigil it already acts as an Array, but when you have a list inside a scalar it will return the Array and not iterate inside it.

The solution is to use .list to make it act as a list instead of as a scalar.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: