Raku / doc

🦋 Raku documentation
https://docs.raku.org/
Artistic License 2.0
287 stars 293 forks source link

next trap #4255

Open coke opened 1 year ago

coke commented 1 year ago

Was just working on one of the xt/ tests, where I had

for @($thing) -> $thing {
    doit()
}

and 10 lines inside of doit, I had a

next if....

instead of a

return if

which ended up skipping in the caller's for loop. I was very confused as to why it was not going through each element.

@cfa suggested this is a trap.

patrickbkr commented 1 year ago

Is it verified this is not a bug?

cfa commented 1 year ago

No, not a bug.

Note that this isn't unique to Raku; Perl[^1] has the same behaviour:

$ raku -e 'sub ponder { next }; for (1..3) { ponder; say $_ }; say "done"'
done
$ perl -E 'sub ponder { next }; for (1..3) { ponder; say $_ }; say "done"'
done

but there, warnings can help identify a potential bug:

$ perl -E 'sub ponder { next }; for (1..3) { ponder; say $_ }; say "done"' -w
Exiting subroutine via next at -e line 1.
Exiting subroutine via next at -e line 1.
Exiting subroutine via next at -e line 1.
done

Accidentally using next, last etc. to exit a sub should probably be detected by the compiler. When the above is intended behaviour, one could opt out of the error / disable the warning (again, as in Perl):

$ perl -E 'sub ponder { no warnings "exiting"; next }; for (1..3) { ponder; say $_ }; say "done"' -w
done

For now, I'd say @coke's example is worth documenting as a trap. Alternatively, we could add some examples demonstrating the use of next etc. within subs for flow control (sub my-next { … next … } and the like).

[^1]: I know Raku isn't Perl but the comparison here is useful, I think?

cfa commented 1 year ago

Alternatively, we could add some examples demonstrating the use of next etc. within subs for flow control (sub my-next { … next … } and the like).

P.S. Instead of "alternatively", perhaps "additionally"?

This behaviour is probably worth documenting as part of control flow anyway.

2colours commented 1 year ago

No, not a bug.

Is it in the specs? If not, I'd still lean towards a fix. A Block should behave like this but not a Sub.

cfa commented 1 year ago

@2colours, I replied there.

2colours commented 1 year ago

Right, thank you... Welp, seems like we cannot get away without taking notes of it, as it appears with last in the specs.

Having said that, it still seems like low-hanging fruit from design perspective, therefore I'd keep the other issue also open.