Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

Pass the Subroutine Name in form action value

by gopalr (Priest)
on Jun 23, 2006 at 07:08 UTC ( #557097=perlquestion: print w/replies, xml ) Need Help??
gopalr has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

I have cgi-script name called main.cgi.

The following code works fine while running the main.cgi when I pass "newcgi.cgi" as an action name.

$query->startform(-method=>'POST', -action=>"newcgi.cgi");

And, there is soubroutine name called "report" in main.cgi.

My question is can we pass the action value as a subroutine.

Thanks in advance!!
Gopal R.

Replies are listed 'Best First'.
Re: Pass the Subroutine Name in form action value
by Corion (Pope) on Jun 23, 2006 at 07:16 UTC

    You can, but you don't want that, because it makes it too easy to use other subroutines in your script. You want to use a table mapping the names to your subroutines like this ("dispatch table"):

    sub report { print "Reporting"; }; sub add { print "Adding"; }; sub frobnicate { print "Frobnicating"; }; my %allowed_actions = ( report => \&report, add => \&add, frobnicate => \&frobnicate, ... ); sub handle_form { my $query = CGI->new(); my $default_action = 'report'; my $action = $query->param('action') || $default_action; # Sanity check if (not exists $allowed_actions{$action}) { warn "Unknown action >>$action<< attempted. Forcing to '$defau +lt_action' instead."; $action = $default_action; }; my $code = $allowed_actions{$action}; # Now, call the code $code->($query); };
Re: Pass the Subroutine Name in form action value
by McDarren (Abbot) on Jun 23, 2006 at 07:15 UTC
    There is probably a more elegant way to do this, but you could do:
    $query->startform(-method=>'POST', -action=>"newcgi.cgi?foo=report");

    And then in newcgi.cgi, you have...

    report() if param('foo') eq 'report';

    Or something along similar lines.

    Darren :)

Re: Pass the Subroutine Name in form action value
by Tanktalus (Canon) on Jun 23, 2006 at 14:45 UTC

    I would recommend that you look at CGI::Application. It sounds like you're on the verge of going there, especially if you take Corion's advice (which you probably should). It really helped me take a whole new look at designing CGI.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://557097]
Approved by GrandFather
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2018-06-19 08:58 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (111 votes). Check out past polls.