in reply to Improving the efficiency of this piece of code

I would probably use a hash for this, with the values as subroutine references. Here's a simple example:
#!/usr/bin/perl -wT use CGI qw(:all); use CGI::Carp qw(fatalsToBrowser); my %dispatch = ( '' => \&index, page2 => \&page2, page3 => \&page3, default => \&index, ); my $page = param('page'); my $subref = $dispatch{$page} || $dispatch{default}; $subref->();

Replies are listed 'Best First'.
Re: Re: Improving the efficiency of this piece of code
by repson (Chaplain) on Feb 25, 2001 at 14:08 UTC
    I'd also consider communing with the almighty vault. It seems that someone else actually has created a multiscreen CGI before....

    CGI::Screen and CGI::Application are the ones I've noticed there. But I haven't actually used them, so I don't know what, (?:dis)?advantages they have compared to a simple hash dispatch method.

      I can personally vouch for CGI::Application's homemade goodness. I found it a tad easier to learn than HTML::Mason while it provides similar functionality. Basically, it provides runtime function callbacks on various invocations of the script with some shortcuts in between. I've find this module killer if combined with HTML::Template (or some other templating mechanism).

      One drawback is that the entire generated HTML must be passed back as a string when you're done- hence the web l0ser will not see any stuff until the script is absolutely done- ala zero NPH capability (or similar capability). This is especially frustrating when used in congruence with DBI. But, as the doctor says when you ask "Doctor, I'm fat in some place!", simply don't use massive amounts of CGI-generated HTML with CGI::Application.

      AgentM Systems nor Nasca Enterprises nor Bone::Easy nor Macperl is responsible for the comments made by AgentM. Remember, you can build any logical system with NOR.
Re: Re: Improving the efficiency of this piece of code
by unixwzrd (Beadle) on Feb 25, 2001 at 06:24 UTC
    I really like this way of doing things. I implement it myself in a lot of my CGI code too. It seems cleaner to me than all the condition testing, and though I haven't benchmarked it, I would assume faster using the hash to dispatch.

    Mike -

    "The two most common elements in the universe are hydrogen... and stupidity."
    Harlan Ellison