5 ms·
I'm pretty new to perl scripting but most of my cgi's at work look like this near the beginning. How is that crazy bit of code better? (Post_only is just a func
by wizard_2 16y ago
I'm pretty new to perl scripting but most of my cgi's at work look like this near the beginning. How is that crazy bit of code better? (Post_only is just a function that returns the function or a 404 if the request isn't a post)
# Dispatcher
my %action = (
'search' => \&controller_search,
'view' => \&controller_view,
'save' => post_only(\&controller_edit),
'delete' => post_only(\&controller_delete),
'index' => \&controller_index,
);
if(exists $action{$q->param('do')}){
$action{$q->param('do')}->();
}else{
$action{'index'}->();
}
exit;
- f00li5h 16y agourls full of ?do=! very tidy example none the less. (running commands was not the best example, i've gotta admit) Thanks for the feedback!
- Xurinos 16y agoTwo quick questions... Why is the name for the function "controller_edit" instead of "controller_save"? Why is post_only checked as part of the dispatch and not inside the two functions? Quickie older-style perl alternative structure where I use AUTOLOAD to figure out the exists/can situation: use strict; use warnings; package Controller; sub search {...} sub view {...} sub save {...} sub delete {...} sub AUTOLOAD { # Do index stuff } ... package main; ... my $method = $q->param('do'); Controller->$method;
- f00li5h 16y agoI didn't know AUTOLOAD could do that... neat!
- dgl 16y agoBeware this could have a huge security hole if you are taking method names from the user like that -- they can include a qualifying package name (normally you see SUPER:: used in this context, but it could be anything loaded). In your example not so much, but if the params to that call were also under the user's control. Say IO::File was loaded and I went to 'do=IO::File::open', I might be able to read/write files.
- Xurinos 16y agoI agree wholeheartedly. Never trust input.
- wizard_2 16y agoI grabbed that out of an older project, most of my newer ones only have a save.