Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: A short, "iffy" rant

by iburrell (Chaplain)
on Oct 11, 2004 at 21:34 UTC ( #398303=note: print w/replies, xml ) Need Help??

in reply to A short, "iffy" rant

Using a hash for dispatch table is great when the select is single valued like that. Sort of like a case statement.

This doesn't work when the expressions in the if/elsif/else are complicated. For example, if the second else had to handle the undef param case. Or there was a case for handling ranges or multiple possibilities with the same code.

Replies are listed 'Best First'.
Re^2: A short, "iffy" rant
by Ovid (Cardinal) on Oct 11, 2004 at 21:41 UTC

    That can still be easily solved with a dispatch table.

    sub _select_fields { my $self = shift; my %rev_types = ( both => sub { # some difficult logic }, total => sub { [qw/foo bar/] }, ); my $rev_type = $self->request->param('rev_type'); $rev_type = 'both' unless exists $rev_types{$rev_type}; return @{$rev_types{$rev_type}->()}; }

    Though as noted above, the $rev_types should probably be moved outside of the sub.

    If necessary, you can also write some code for generating a hash key based upon the difficult logic. This has the advantage of cleanly encapsulating the logic for each case rather than embedding it in the if/elsif/else constructs.


    New address of my CGI Course.

      I guess its time to make my standard plug to use Exporter::Dispatch... although this case is probably too simple to warrant the module.

        What problem were you trying to address when you wrote this?

        My feeling is that for the effort of creating a new package (likely in its own file), and importing a module, you get to write sub foo {...} rather than foo => sub {...}, - but I don't see the syntax change as mattering much while I do see that overhead as mattering quite a bit.

        Furthermore rather than seeing closures as an unnecessary complication, I see them as an opportunity. You can ignore the fact that you can use closures to fill in the table. But if you need it, you have the ability to use closures to autogenerate large portions of your dispatch table.

        And a further hash advantage - you are allowed names that would not easy or (in some cases) legal in Perl function names.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://398303]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2023-12-11 13:17 GMT
Find Nodes?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?

    Results (41 votes). Check out past polls.