Forum Moderators: coopster & phranque

Message Too Old, No Replies

How to test for uninitialized value

Before the script blows up

         

runner

1:51 am on Oct 25, 2006 (gmt 0)

10+ Year Member



I can't remember how to test a scalar to see if it is uninitialized before being used. I am writing a cgi script in perl and in the development process I have found a place where it is possible for a particular scalar $article to be uninitialized. I want to test for this condition so it can be corrected before the scalar is used somewhere and blows chunks.

I've done this before but I can't remember what I did. I've googled and searched but I guess I'm not using the correct search words. I'm getting really frustrated!

runner

1:56 am on Oct 25, 2006 (gmt 0)

10+ Year Member



I think I'll give the variable a default value and then check to see if it is still set to that value before I use it.

runner

1:59 am on Oct 25, 2006 (gmt 0)

10+ Year Member



Darn, that won't work...

runner

2:14 am on Oct 25, 2006 (gmt 0)

10+ Year Member



OK I found it!

{
no warnings 'uninitialized';
if ( CGI::param('name') ) {
print "Hello, " . CGI::param('name');
}
else {
print "Hi there.";
}
}

wruppert

3:32 am on Oct 25, 2006 (gmt 0)

10+ Year Member



The "defined" function tests for uninitialized vars -

$var = '' unless defined $var;

or

$var ¦¦= '';

or

if (!defined($var) {do stuff}

perl_diver

4:51 pm on Oct 25, 2006 (gmt 0)

10+ Year Member



for form data you not only want to check if it's defined but also if it's valid. If all you do is check to see if it's defined a person can enter something as useful as a single space character in the form widget and your script will accept that as the value.