Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Get a CGI::param() variable with undef checking.

by monoxide (Beadle)
on Nov 11, 2004 at 04:07 UTC ( #406909=snippet: print w/replies, xml ) Need Help??
Description: Allows you to get a CGI parameter without worrying about whether it is defined (a big problem i had with use diagnostics). It also allows for a default value.
Update: Added a default default value....
use CGI;

# Gets a HTTP paramater from CGI->param() with error checking.
# $_[0] = param to get
# $_[1] = default value if the param is not defined
sub getparam
{
  $query = new CGI;
  ($param, $value) = (@_,"");
  if (defined(CGI->param($param)))
  {
    return CGI->param($param);
  } else {
    return $value;
  }
}
Replies are listed 'Best First'.
Re: Get a CGI::param() variable with undef checking.
by Your Mother (Archbishop) on Nov 13, 2004 at 08:17 UTC

    I think you probably don't want to create a new CGI object every time you call the sub. It would be expensive and there's no need. The call style ( @_, '' ) is kinda weird too and would fail under strict as written. Here's a redraft.

    use CGI (); # at top of script/module # transparently take over function param() if desired sub param { my $param = shift || return; my @values = CGI::param($param); return '' unless @values; return wantarray ? @values : $values[0]; }
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://406909]
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: (5)
As of 2021-03-03 15:19 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favorite kind of desktop background is:











    Results (80 votes). Check out past polls.

    Notices?