Scimon Proctor's answer is essentially correct, but I'll try to explain why your example does not work. For starters, kv
returns "an interleaved sequence of indexes and values", so this:
my @s=<a b c d>;
.say for @s.kv;
prints
0
a
1
b
2
c
3
d
Essentially, you're doing one turn of the loop for every key and value. Grouping them in pairs using rotor
might be closer to what you're looking for:
.say for @s.kv.rotor(2)
which will return:
(0 a)
(1 b)
(2 c)
(3 d)
Since with this we got the value couple with the index, we can do...
my @s=<a b c d>;
for @s.kv.rotor(2) -> ($k, $) {
"{@s[$_]} ".print for ($k..^@s.elems);
printf("\n");
}
Please note that there was also an error in the inner loop, whose range went beyond the actual indices in @s. But, again, Scimon's answer that uses maps is much shorter, idiomatic and straightforward. This one is just kind of dwimming your original program. As a matter of fact, we are throwing away the values, so this would actually be:
my @s=<a b c d>;
for @s.keys -> $k {
"{@s[$_]} ".print for ($k..^@s.elems);
printf("\n");
}
No need to use kv at all, and just make do with the keys.