sierrathedog04 has asked for the wisdom of the Perl Monks concerning the following question:

Yesterday I spent two hours debugging one of my CGI.pm scripts. I could not figure out why param('myfield') was returning an empty string.

Then I realized that the text field I was calling existed on a different form than the one I was submitting. Yet CGI.pm's param() function did not return an error when I called this non-existent field.

Using CGI.pm there appears to be no way to tell at runtime whether param('myfield') is returning an empty string because:

  1. the user did not enter any response; or
  2. the submitted form does not include form variable by that name.

Is there any way to force CGI.pm to return an error when I call the param() function for a parameter that does not exist?

  • Comment on Any Way To Distinguish Undef From Empty Parameters When Using CGI.pm's Param() function?

Replies are listed 'Best First'.
Re: Any Way To Distinguish Undef From Empty Parameters When Using CGI.pm's Param() function?
by Masem (Monsignor) on Jun 01, 2001 at 20:25 UTC
    In CGI.pm versions 2.63 and above, you should be able to check the defined() of what is returned; if the keyword is there but no value, you'll get an empty, but defined string. EG:
    my $value = defined( $cgi->param( 'text' ) ) ? $cgi->param( 'text' ) : '';

    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
Re: Any Way To Distinguish Undef From Empty Parameters When Using CGI.pm's Param() function?
by bikeNomad (Priest) on Jun 01, 2001 at 20:22 UTC
    param('noSuchKey') seems to return undef if there is no such field, so you can use defined:
    my $param = param('whatever'); if (!defined($param)) { # do something }
Re: Any Way To Distinguish Undef From Empty Parameters When Using CGI.pm's Param() function?
by merlyn (Sage) on Jun 01, 2001 at 21:13 UTC
    Browsers are free not to return unfilled fields. What will you do then?

    But as for detecting the differences between an unsent field and a sent field, the other answers in this thread are fine, to use the defined function.

    -- Randal L. Schwartz, Perl hacker