Home: Perl Programming Help: Beginner:
Is there a way to force undef to be undef, instead of 0?



zp
New User

Aug 22, 2013, 1:41 AM


Views: 3204
Is there a way to force undef to be undef, instead of 0?

I know perl default an undefined variable to 0 when it mixes with numbers.

my $a = undef;

my $b = $a -1; ##the result of b is -1, not undef

Is there a way that i can get undef instead of -1 for b?


FishMonger
Veteran / Moderator

Aug 22, 2013, 7:09 AM


Views: 3202
Re: [zp] Is there a way to force undef to be undef, instead of 0?


Code
use Data::Dumper; 

$foo = undef;
$bar = ($foo -1) < 0 ? undef : $foo - 1;

print Dumper $bar;



Laurent_R
Veteran / Moderator

Aug 22, 2013, 9:56 AM


Views: 3196
Re: [zp] Is there a way to force undef to be undef, instead of 0?


In Reply To
Is there a way that i can get undef instead of -1 for b?


I don't think you can. If you declare a variable with;

Code
my $foo;

it is undefined, which you can test with the defined function:

Code
print "foo is undef" unless defined $foo;

But it you increment or decrement $foo, or add or substract a number, $foo is transformed into 0 before the arithmetic operation is made. This is plausibly an application of the followinf principle: "the Perl compiler/interpreter is trying to do what you mean."

If you need undef to be propagated to other variables, you'll have to test yourself (or possibly create a class that overloads the arithmetic operators, but that seems to be overkill).


BillKSmith
Veteran

Aug 22, 2013, 10:45 AM


Views: 3194
Re: [zp] Is there a way to force undef to be undef, instead of 0?

Combining Fishmonger's and Laurent's reply, you could use:

Code
$b = (defined $a) ? $a - 1 : undef;


Laurent's other suggestion to define a class of numbers with the desired semantics probably is the way to go on a large project (or a group of related progects). The module that defines such a class probably should be shared in CPAN.
Good Luck,
Bill


zp
New User

Aug 22, 2013, 7:15 PM


Views: 3184
Re: [zp] Is there a way to force undef to be undef, instead of 0?

Thank you all for the suggestions.