in reply to given/when one case prefixes another

This works in Strawberry 5.10.1.4, but I don't know how 'proper' it is; frankly, it looks a bit hinky to me.

>perl -wMstrict -lE "for my $s qw(a b c d) { given ($s) { when ('a') { say 'a'; continue; } when ('b') { say 'b'; continue; } when (/[ab]/) { say ' after a or b'; } say 'neither a nor b'; when ('d') { say 'd'; } default { say qq{other: '$_'}; } } } " a after a or b b after a or b neither a nor b other: 'c' neither a nor b d

BTW: I couldn't get the goto approach to work: Perl experiences a 'panic: goto' attack.

Replies are listed 'Best First'.
Re^2: given/when one case prefixes another
by moritz (Cardinal) on Apr 26, 2011 at 09:03 UTC

    It seems like perfectly fine code to me.

    I guess you are wondering if the code directly in "given" (without a "when" clause) is "proper". The answer is yes. That's one feature that distinguishes given/when from the switch statement in C.

    But do consider that such code could become hard to read if the whole given/when doesn't fit onto one or two screen pages anymore - you shouldn't be doing very much in the when clauses (calling functions or methods should be fine).

      I suppose I was uneasy about the possibility of the  when (/[ab]/) { ... } tail clause 'getting lost', dependent as it is on a  continue statement in other, possibly distant, clauses, and on the relative positions of those clauses (also a dependency of Neighbour's approach). Taking apl's suggestion, I am more comfortable with something like the following, which encapsulates the tail of each 'tailed' clause within the clause itself:

      >perl -wMstrict -lE "for my $s qw(a b c d) { given ($s) { my $tail_a_and_b = sub { say qq{ after a or b, was '$_' } }; when ('a') { say 'a'; $tail_a_and_b->(); } when ('b') { say 'b'; $tail_a_and_b->(); } when ('d') { say 'd'; } default { say qq{other: '$_'}; } } } " a after a or b, was 'a' b after a or b, was 'b' other: 'c' d