loopsrakupositional-parameter

Using a loop's positional parameters inside an inner loop in Raku


Here is the code:

my @s=<a b c d>;
for @s.kv {
    for ($^k ... @s.elems) {
        printf("%s ", $^v);
    }
    printf("\n");
}

Expected output is:

# a b c d
# b c d
# c d
# d

But it gives this error (possibly among others)

key 0, val 1 Too few positionals passed; expected 2 arguments but got 1

It looks like the positional variables of the main loop $^k and $^v can't be used inside the inner loop. How to fix it? Thanks. Update: Typo inside inner loop fixed


Solution

  • So for what you want to do I'd approach it like this :

    my @s = <a b c d>;
    for ^@s.elems -> $start-index {
        for @s[$start-index..*] -> $value {
            printf("%s ", $value );
        }
        print("\n");
    }
    

    Though really I'd do this.

    my @s = <a b c d>;
    (^@s.elems).map( { @s[$_..*].join(" ").say } )
    

    Get the range from 0 to the number of elements in the array. Then the slice from there to the end for each, join on spaces and say.

    A note on variables like $^k these are scoped to the current block only (hence why your above code is not working). Generally you only really want to use them in map, grep or other such things. Where possible I'd always advise naming your variables, this makes them scoped inside inner blocks as well.