I like dispatch tables. Which means I use this kind of thing quite a bit:


if exists $dispatch{$pieces_of_state};

Does that sub-routine call look ugly? I suspect it does. It would look nicer in javascript for sure:


But how much difference does the syntax really make? I understand the impulse to make perl look more like Haskell but I doubt very much that the extra noise from the sigils makes a lasting difference to the readability/maintainability of the code.

Which is not to say that notation is not important - it is - but it can only get you so far. You still have to understand the concepts behind the notation. I could use source filters and come up this something like:

dispatch :

Free of sigils and arrows but - well - so what? I still have to mentally reconstruct the text into "table", "condition", and "inputs" clauses.

What is more important in this case is why I'd use a dispatch table in the first place. I can
ruthlessly weed out:

* Irritating if-else clauses
* Obfuscating unless's
* Stupefying switch's.

In short the code becomes more concise. And more beautiful, at least to my eyes.


Wouldn't this be better?


You don't really need the arrow: $actions{$chosen}(@inputs); works just like $AoH[1]{foo} vs. $AoH[1]->{foo}.

The arrow does provide a clue that you're calling a subroutine, so I leave the arrow in, while omitting it with nested data structures.

I actually like to use dispatch($state)->(@args) where dispatch() returns a coderef to the chosen function. This makes it easier to handle default cases and invalid values for $state, and makes it easier to handle more advanced dispatch logic by just changing the dispatch...err..dispatcher. :)

This is a link to the dispatch table section of the HOP book:

Leave a comment

About mrstlee

user-pic Is it just me or is perl too much fun to be shared with the unworthy?