tobyink / p5-match-simple

Perl 5 distribution match-simple; see homepage for downloads and documentation.
https://metacpan.org/release/match-simple
4 stars 3 forks source link

document warnings etc if nested, and workarounds (sugar only) #6

Open n1vux opened 2 weeks ago

n1vux commented 2 weeks ago

when using match::simple::sugar (with Data::Enum that now supports match::simple !), when nesting the switch for () { when ..., then{}; ...} non-looping loop block within an outer for(), foreach() or while(<>){} actual loop ~as one does~, whether as an event loop or per-line-input loop, there are three implications that should be documented; one of which might be fixable in module code.

  1. the outer loops must use a named loop variable, or (minimally invasive) have a local my $line=$_; just before the SWITCH: for when, and any and all implicit m{}, //, etc or explicit references to $_ must be changed to $line =~ m{}.
  2. outer and inner loops need LINE: while(<>){...} and SWITCH: for ($STATE){when .. statement labels, as when...then will do next on the inner for as if it were a loop, so script's own loop control next, redo, last must name next LINE;.
  3. to avoid a ~flurry nay~ blizzard of Exiting subroutine via next at warnings on STDERR, must insert no warnings 'exiting'; after SWITCH: for ($var){ .

I would not put the no warnings outside the for-when lexical block, so as to not block warnings caused by other errors.

It might be practical to inject the no warnings 'exiting'; into the anon-subs made from the then {block} ?

(Near as i can tell, there's no danger of an innermost loop inside the then{} clause having a problem, as the hidden next SWITCH by the when occurs after the then{} anon sub returns to when, if i don't next LINE; out of it.)

n1vux commented 1 week ago

Additional warning required

that return in the then {BLOCK} won't do what is expected, but rather returns from the when-then anon-sub (lambda).

Would need to return up the call stack to return from my visible sub.

(Instead i just use save a $ret value the way we used to do when one in one out structured programming forbade return from anywhere except the bottom of the subroutine. )

(Aside: Probably helped that I'm old enough to have suffered under that formalism. Which did let us reason over programs, and I have proved several production loops correct according to precondition, invariant, progress, postcondition, which benefited from no early exits / no gotos. But readable code is more useful most of the time. :rofl: )