Forum Moderators: coopster & phranque

Message Too Old, No Replies

Command lookup and dispatch in Perl

         

Brett_Tabke

9:16 pm on Mar 12, 2001 (gmt 0)

WebmasterWorld Administrator 10+ Year Member Top Contributors Of The Month



What constructs do you use for command lookup tables?

I have an app that has 100+ user commands available as discret subroutines of the main app - seems like there should be an easy way to manage all that.

I'm experimenting with something along these lines:

%cmds =(
mainscreen => "User login",
viewmsg => "User Viewing Message"
)
# $action is passed by user (routine is actually much larger to account for cmd misses

foreach $key (keys %cmds) {
print "Command: $cmds{$key}";
&$key if $key eq $action;
}

--
I know, everyone says not to use that, and I generally agree that variablized subroutine calls is not a great move to make. However; the above is really slick and offers good control.

You have any favorites?

sugarkane

11:56 pm on Mar 12, 2001 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



That is pretty slick... what concerns do you have with the variabalised approach though?

Something fun to play with:

my %cmds = (
"User Login" => "mainscreen",
"User Viewing Message" => "viewmsg"
);

$cmds{$action}->();

I'm not entirely sure what's going on here, but it seems to be relying on the fact that Perl sees your app as a package called 'main', and passing the subroutine name to that package causes main::sub_name to be executed, which is equivalent to a subroutine call.

This seems to be heading in the Object Oriented direction, where I have so far feared to tread...

sugarkane

9:54 am on Mar 13, 2001 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



OK, scrub my speculation on what was happening in the above post. This is actually about 'hard references', and a cleaner way to do it would be

my %cmds = (
"User Login" => "\&mainscreen",
"User Viewing Message" => "\&viewmsg"
);

# sanity check $action here

$cmds{$action}->();

littleman

5:31 pm on Mar 13, 2001 (gmt 0)



Why would variable subroutine calls be a no no?

sugarkane

6:22 pm on Mar 13, 2001 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Variable sub calls of this kind would fail if you were using the 'strict' module. strict is supposed to protect you from 'unsafe constructs' - it forces you to predeclare variables etc, and generally code in a cleaner way, which could be helpful in a large project.

For example, if you mistyped a variable name in some deep part of your code, when run without strict Perl would create a new variable with the typo'd name, probably leading to much confusion. With strict, this would generate an error because the variable hasn't been seen before, giving a much clearer indication of where the problem is.

Quite why strict objects to using subroutine references... well, I haven't got to that chapter yet ;)