PDA

View Full Version : undef value


macchisp
08-02-2006, 09:25 PM
I am passing parameters through my perl scripts and sometimes the parameters can be undefined. If they are undefined, I want to set them to a specific value.

Here is a snippet of my code:
my $num = param('num');
if(undef($num)) {$num = 5;}


print "$num";

I am purposly giving it an undefined value because I want to check it using print. When I do this, I get a warning that says "use of uninitialized value in concatenation (.) or string in line 21..." Every other part of the script works, except this print method, nothing gets printed and I think it's because it is still undefined. It runs fine but I don't want to make the error log longer than it has to be. I'm trying to make my code efficient.

How can I get it to define the value to 5? Are there any other ways that are better?

Thanks for your help.

ralph l mayo
08-03-2006, 12:26 AM
undef() isn't a test, it just removes the definition of its argument(s), so your if statement is just clobbering the data every time, after which the condition evaluates to false and the default assignment can never be triggered.

Change the condition to if (!defined $num)

FishMonger
08-03-2006, 01:20 AM
my $num = param('num') || 5;

print $num;

KevinADC
08-03-2006, 05:48 AM
nothing wrong with FishMongers suggestion, I do that all the time myself, but if you ever had to check if a scalar is not defined use the defined() function, which will check if the scalar has any value what-so-ever, even undef:

if (!defined($num)) {$num = 5}

or:

unless (defined($num)) {$num = 5}

or using the ternary operator:

$num = (defined($num)) ? $num : 5;


if on the other hand you want to assign a default value to a scalar which has a value of undef or zero or "" (empty string) use FishMongers suggestion.

macchisp
08-03-2006, 04:54 PM
Thank you all...it worked great.

KevinADC
08-03-2006, 06:09 PM
oops, I have to correct myself. defined() will return false if the scalar has a value of undef. But it will return true if the scalar has a value of zero (0) or the empty string.