Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Re: Why is my CGI.pm script trying to assign data before pressing submit.

by Amoe (Friar)
on Dec 07, 2001 at 22:08 UTC ( #130262=note: print w/ replies, xml ) Need Help??


in reply to Re: Why is my CGI.pm script trying to assign data before pressing submit.
in thread Why is my CGI.pm script trying to assign data before pressing submit.

In cases like this, it can be cleaner to use a hash lookup table:

my %lookup = (edit => sub { let_the_user_edit_it() }, preview => sub { preview_it() }, commit => sub { commit_to_get_fit() }); $lookup{param('state')}->();


--
my one true love


Comment on Re: Re: Why is my CGI.pm script trying to assign data before pressing submit.
Download Code
Hash lookups vs. elsif for case.
by TGI (Vicar) on Dec 10, 2001 at 07:27 UTC

    I thought I'd stick with the basic technique of an if else chain, to keep things simple on the perl end of things. But, if you don't mind working with references (which are something every perl programmer should learn to use), a hash of subroutine refs is a most excellent technique.

    my %lookup = (edit => \&let_the_user_edit_it, preview => \&preview_it, commit => \&commit_to_get_fit, ERROR => \&non_existant_state ); if exists $lookup{param('state')} { $lookup{param('state')}->(); } else { $lookup{ERROR)}->(); }

    I made a couple of changes to your code. Storing the subroutine addresses directly, saves one round of subroutine dispatch, a negligable performance savings, but it removes 1 level of indirection and saves on typing--to my mind, it's tidier. I also check for the existance of the hash key before trying to execute its code reference. This lets you give a better feedback in your error page than a plain 500 error usually does.


    TGI says moo

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://130262]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (12)
As of 2014-12-26 15:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (171 votes), past polls