hacker has asked for the wisdom of the Perl Monks concerning the following question:
With the help and patience of wfsp, Anno and others on the CB, I was able to trim out some fat in my existing dispatch tables for a site I'm rewriting.
What I'm currently left with (which works, so far), is this:
my %dispatch = ( home => \&home, donate => \&donate, news => \&news, samp => sub { \&samples($dbh) }, ... ); $action = $apr->param('a') || 'home'; $dispatch{$action}->($action); sub render_template { my ($action, $params) = @_; my $template = HTML::Template->new( die_on_bad_params => '0', filename => "$action"); my $content = $template->output; print $content; } sub home { my ($action, $params) = @_; return render_template($action, $params); } sub donate { my ($action, $params) = @_; return render_template($action, $params); } sub news { my ($action, $params) = @_; return render_template($action, $params); } sub samples { my ($dbh) = shift; .... }
Note: There's one small bug I just found when composing this (if I pass an unknown param, it should default to 'home', but it doesn't, it just dies with Can't use string ("") as a subroutine ref while "strict refs" in use). I'll try to fix that shortly.
What I'm wondering now, is with these subs being identical now except for their sub name... can I make these into anonymous subs, and pass the $action down to them, reducing the 20+ identical subs down to 1?
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Reducing the complexity of dispatch tables
by ikegami (Patriarch) on Aug 31, 2007 at 15:15 UTC | |
Re: Reducing the complexity of dispatch tables
by jdporter (Paladin) on Aug 31, 2007 at 16:43 UTC | |
Re: Reducing the complexity of dispatch tables
by BrowserUk (Patriarch) on Aug 31, 2007 at 17:15 UTC | |
by moritz (Cardinal) on Aug 31, 2007 at 17:48 UTC | |
by BrowserUk (Patriarch) on Aug 31, 2007 at 18:15 UTC | |
by jdporter (Paladin) on Aug 31, 2007 at 19:12 UTC | |
by BrowserUk (Patriarch) on Aug 31, 2007 at 19:22 UTC |