in reply to Redirection within a Perl script

The for ($funct) { ... } one-time loop is better written as

{ local $_ = $funct; #... }
but switches are awkward things in perl. They are always a scan over a bunch of conditions. You can only group the most frequent requests first to improve them.

Another way, tidier I think, is to build a dispatch table of the coderefs,

my %action = ( 'Save News' => \&savenews, 'Save Book' => \&addbook, 'Save Observ' => \&addobserv, 'Save Rule' => \&addrule, # ... 'Next' => \&viewbooks, 'Prev' => \&viewbooks, );
Now you can call any action by $action($funct}->() or default(); (for some sub default). I've eliminated the case insensitivity, since the keys ought to be coming from your form.

Update: runrig++ is wise to suggest checking for existence of the $func key. His trinary op for calling is better than what I showed. I forgot to mention that the CGI::Application module provides a good wrapper for this sort of thing.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Redirection within a Perl script
by bradcathey (Prior) on Dec 04, 2003 at 03:18 UTC
    Thanks Zaxo. As I mentioned in my reply to runrig, I'm not getting the dispatch tables immediately, but your example helps and I'll go ahead and try it, without understanding it completely, and maybe it will become clearer as I go. Not very orthodox, but I'm probably not the first coder to write something I don't fully understand, and have it work :-)

    Update:
    Googled, found lots of examples, but none as clear as in above replies. So, started with code posted here, and after some minor explosions, got it. Here's a distilled sample that puts it all together. Thanks all!
    #CGI stuff and parsing form here ... my $funct = param('funct'); #button user clicks my %action = ( 'Save News' => \&savenews, 'Add Book' => \&addbook, ); ( $action{$funct} || \&default )->(); sub savenews { print "save news\n"; } sub addbook { print "add book\n"; } sub default { print "not a choice\n"; }

    —Brad
    "A little yeast leavens the whole dough."