in reply to Re^2: Avoiding if/else knots II
in thread Avoiding if/else knots II

TIMTOWTDI - I wanted to give an example of the m// && do {} idiom which was missing from the OP's previous thread. Since I don't know about the specifics, I wrote it somewhat generic. Depending on cases the $key or $case could be modified etc.

As for your example, what good is it to use a labelled loop for a list containing one variable? ;-)

--shmem

_($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                              /\_¯/(q    /
----------------------------  \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Replies are listed 'Best First'.
Re^4: Avoiding if/else knots II
by Skeeve (Parson) on Aug 30, 2006 at 10:09 UTC
    As for your example, what good is it to use a labelled loop for a list containing one variable? ;-)

    That's easy.

    1. The label is there to show that the block is emulating as a SWITCH statement.
    2. The label is also there to show what the last statements refer to.
    3. the for with just one variable is simply there to assign $value to $_ without explicitly doing it
    4. it's also there to keep the original content of $_ outside the SWITCH ("loop"). Try this
      my $v="V"; $_="_"; for ( $v ) { print "inside: $_\n"; } print "outside: $_\n";
    5. It looks good ;-) (to me). I read this as "switch for value ..."

    s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
    +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e
      It looks good ;-) (to me). I read this as "switch for value ..."

      Ah, style. Still, I deem it a misuse of for. It sets up the context of a loop whilst none needed.

      This one looks better (for me, that is :-)

      # SWITCH { local $_ = $MyValue; /$reg2/ && do { sub_for_key_a(); last; }; /$reg1/ && do { whatever(); sub_for_key_b(); last; }; #default sub_for_default(); } # END SWITCH
      since a bare block does the job and is less clutter. And I also read it as "switch for $MyValue" ;-)

      --shmem

      _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                    /\_¯/(q    /
      ----------------------------  \__(m.====·.(_("always off the crowd"))."·
      ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

        It wasn't my idea. I took it from "Programming Perl" by Wall, Christiansen & Schwartz. Chapter 2: You might think it odd to write a loop over a single value, but a common idiom for a switch statement is to use foreach's aliasing capability to make a temporary assignment to $_ for convenient matching.


        s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
        +.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e