Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys.I've got a question about using a cgi form to call a subroutine. What I want to do is define a subroutine within the same script as the form, then reference the it as the form's action.I more or less understand how to call a subroutine from an external file - i.e.
print '<form action="someCGI.cgi">';
or something like that.What I'm looking at doing is something on the order of:
sub mySub{ (my code) }
and then either
print '<form action=&mySub>';
or
print start_form(-action=>&mySub);
My syntax probably needs work, but I could swear I got this to work before - just can't remember how. Can anyone either give me a hint on how to do this, or if there's a better way?Thanks.

Replies are listed 'Best First'.
Re: call subroutine from cgi form
by mr_mischief (Monsignor) on Aug 13, 2008 at 19:46 UTC
    To expand on chromatic's advice, try something along these lines:
    if ( $cgi_query->param('action') eq 'sub_1' ) { sub_1(); } elsif ( $cgi_query->param('action') eq 'sub_2' ) { sub_2(); } else { default_sub(); }

      Or, to expand further, and depending on the actual number of subroutines, use a dispatch table:

      ($dispatch{ $cgi_query->param('action') } || \&default_sub)->();
      --
      If you can't understand the incipit, then please check the IPB Campaign.
Re: call subroutine from cgi form
by chromatic (Archbishop) on Aug 13, 2008 at 19:31 UTC

    Pass a parameter in the request portion of the action attribute, and check for that parameter in the program:

    <form action="my_prog.cgi?action=some_action">
Re: call subroutine from cgi form
by trwww (Priest) on Aug 14, 2008 at 00:18 UTC

    Can anyone either give me a hint on how to do this, or if there's a better way?

    CGI::Application can map a cgi parameter to a perl subroutine. It even takes care of setting up http headers for you. Given the type of question you are asking, it will take care of countless issues you would otherwise encounter while trying to develop web apps:

    #!/usr/bin/perl use warnings; use strict; MyApp->new->run; package MyApp; use base qw(CGI::Application); use CGI::Application::Plugin::AutoRunmode; sub mySub : Runmode { return "Hello from mySub\n"; }

    Here is what happens when you run it from a terminal:

    $ ./runmode.cgi rm=mySub Content-Type: text/html; charset=ISO-8859-1 Hello from mySub

    trwww