Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

cgiparam

by stephen (Priest)
on Jan 16, 2001 at 23:04 UTC ( [id://52308]=sourcecode: print w/replies, xml ) Need Help??
Category: CGI Programming
Author/Contact Info stephen <steven@jubal.com>
Description: Sometimes I stumble into hard-to-trace bugs because I've misspelled the name of a CGI parameter-- I use
param('username')
in one place, and
param('user name')
in another. What I wind up doing is defining constants like so:
use constant USERNAME_PARAM => 'username'; print "User name is: ", param(USERNAME_PARAM);
This gets old pretty quickly, though. Recently I started to wonder: what if I could set up a way so that I could just set up subroutines automatically to return a named parameter, a la constant.pm?

So I wrote up cgiparam.pm. Using it, one could have a file like so:

use strict; use CGI ':cgi'; use cgiparam (FOO_PARAM => 'foo', BAR_PARAM => 'bar', BAZ_PARAM => 'baz'); print STDOUT "Foo is ", FOO_PARAM, "\n", "Bar is ", BAR_PARAM, "\n", "Baz is ", BAZ_PARAM, "\n";
And you'll get the values of the CGI parameters foo, bar, and baz in the printout. Plus, you're still using strict, so if you try to use an unspecified parameter, you'll get a compile-time error.

I've tested this once, but have no idea if it's useful...

UpdateWith help from tye, I've added lvalue capability to the code. So now you can do things like:

use CGI ':cgi'; use cgiparam FOO_PARAM => 'foo'; FOO_PARAM = 'blibble'; print STDOUT FOO_PARAM;
and out will come 'blibble'.

Further update Altered the module so that you can supply the names for your own routines, plus removed the direct reference to CGI.pm there so that one can use CGI::Fast. In the future, I'll have the thing check to see if CGI has been loaded (if possible) and load it as necessary.

package cgiparam;

use strict qw(vars);

sub import {
    my $package = caller;
    my $type = shift;
    my (%params) = @_;

    while ( my($subname, $param) = each %params ) {
    *{ "${package}::${subname}" } = sub :lvalue { wantarray ? @{ $CGI:
+:Q->param_fetch($param) } : $CGI::Q->param_fetch($param)->[0]; };
    }

}

1;
Replies are listed 'Best First'.
(tye)Re: cgiparam
by tye (Sage) on Jan 16, 2001 at 23:22 UTC

    Is it just me, or does this just scream ":lvalue"?

    If you have perl 5.6 or later, you could allow:

    FOO_PARAM= "New value";
    pretty easily.

            - tye (but my friends call me "Tye")

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others taking refuge in the Monastery: (8)
As of 2024-04-18 06:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found