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?
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...
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 ;)