http://www.perlmonks.org?node_id=137815


in reply to (ichimunki) Re: Thoughts on Perl6 - Love it? Hate it?
in thread Thoughts on Perl6 - Love it? Hate it?

Switch? Not terribly big deal to me either way. I can see it's value if you want to do some sort of goto-based dispatch, and yes I consider it an improvement over a hash full of coderefs since the conditions in a switch can be more involved that the simple labels that are hash keys. Enough languages have this that there's no reason to avoid it.

I have to disagree with you here. What's wrong with the following?

my %SomeHashWithCoderefs = ( FOO => \&foo, BAR => \&bar, BAZ => \&baz, ); sub Switcheroo { my @conditions = @_; # Using the @conditions, return 'FOO', 'BAR', or 'BAZ' } # In some main area... $SomeHashWithCoderefs{Switcheroo(@args)}->(@otherargs);

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Replies are listed 'Best First'.
(ichimunki) Re x 3: Thoughts on Perl6 - Love it? Hate it?
by ichimunki (Priest) on Jan 10, 2002 at 23:17 UTC
    Because FOO, BAR, and BAZ are not conditions, they are static labels. Is there a way to get them to behave as ranges or any sort of boolean? If so, I still don't have a problem with switch, but I would be glad to have another trick up my sleeve. :)
      Yah, there is.
      sub Switcheroo { my @conditions = @_; if ($conditions[0] < 10) { return 'FOO'; } else { return 'BAR'; } }
      The point is to encapsulate the strategy of determining which direction to go. That's what a switch statement does. This is, basically, a Switch object. (An example of a Strategy pattern, for those following along at home.)

      ------
      We are the carpenters and bricklayers of the Information Age.

      Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

        Your example methodology adds not one, but two layers of indirection to what is otherwise a straightforward question-- and gets none of the fall through capability of the typical switch statement at the same time. It is therefore less than optimal in situations where switch is designed to be most used.

        The one place your indirect method absolutely shines is when you want to set up a mutating hash of anonymous subs (the dispatch table essentially). You keep your condition tree static perhaps (or the condition tree could be just another dispatch (or dispatches!) in the dispatch table). Then you can swap different subs in an out for the same results/conditions labels. Although I'd have to wonder if you can do this for any non-trivial, non-proof of concept application and maintain your sanity or the application later. *grin*