[Purdue-pm] Perl 5 Dispatch Tables

Dave Jacoby jacoby.david at gmail.com
Tue May 28 16:34:39 PDT 2019


I also don't see how dispatch tables violate DRY. I think the better way to
consider them as a special case statement (without fallthrough).

Consider perlbrew. Some of the commands are init, install, switch and use.

if ( $ARGV[0] eq 'init' ) { initialize() }
else if ( $ARGV[0] eq 'install' ) { install(@ARGV) }
...
else { say 'Not a valid command' }

or

use Switch;
switch( $ARGV[0] ){
    case 'init' { initialize() }
    case 'install' { install( @ARGV ) }
...
    else { say "Not a valid command" }
}

becomes

my %dispatch {
    'init' => &initialize ,
    'install' => &install,
}

if ( defined $dispatch{ $ARGV[0] } ) {
    &$dispatch(@ARGV) ;
} else { say "Not a valid command" }

With some playing around, you can check $ARGV[0] against keys %dispatch,
finding the Levenshtein distance, to respond to a typo like "imit" with
'did you mean "init"?' This last way *IS* pretty much how perlbrew works.



On Tue, May 28, 2019 at 3:25 PM Joe Kline <gizmo at purdue.edu> wrote:

> Mark,
>
> I'm not sure how a typical dispatch table is violating DRY.
>
> What I typically do is something like:
>
> my ($dispatch_table) = create_dispatch_table($config_info_if_needed);
>
> sub create_dispatch_table ($config) {
>   my $dispatch = {
>   'thing_one' => \&thing_one,
>   'thing_two' => \&thing_two,
>   };
>   return($dispatch);
> }
>
> I typically don't have some subs I'm calling but directly calling an
> anonymous sub go in there without creating a defined sub.
>
> I have been using the table something like:
>
> $key = q(some token or task based on a keyword);
>
> if ( exists $dispatch->{$key} ) {
>   ($some_ref) = $dispatch->{$key}->($key, $some_arg, $another_arg, $baz);
> }
>
>
> As near as I can detail I'm not using the same code over again in a copy
> and paste fashion.
>
> The only repeating is the variable name the table is hanging out in and
> maybe the key used to call the associated sub ref.
>
> joe
>
> _______________________________________________
> Purdue-pm mailing list
> Purdue-pm at pm.org
> https://mail.pm.org/mailman/listinfo/purdue-pm
>


-- 
Dave Jacoby
jacoby.david at gmail.com

Don't panic when the crisis is happening, or you won't enjoy it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.pm.org/pipermail/purdue-pm/attachments/20190528/30d74e4e/attachment-0001.html>


More information about the Purdue-pm mailing list