CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

Post #1 of 5 (773 views)
Is there a way to force undef to be undef, instead of 0? Can't Post

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

Post #2 of 5 (771 views)
Re: [zp] Is there a way to force undef to be undef, instead of 0? [In reply to] Can't Post


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

Post #3 of 5 (765 views)
Re: [zp] Is there a way to force undef to be undef, instead of 0? [In reply to] Can't Post


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

Post #4 of 5 (763 views)
Re: [zp] Is there a way to force undef to be undef, instead of 0? [In reply to] Can't Post

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

Post #5 of 5 (753 views)
Re: [zp] Is there a way to force undef to be undef, instead of 0? [In reply to] Can't Post

Thank you all for the suggestions.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives