Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, is there graceful way to convert undef to 0 manually?

Tags:

perl

undef

I have a fragment in this form:

my $a = $some_href->{$code}{'A'}; # a number or undef
my $b = $some_href->{$code}{'B'}; # a number or undef
$a = 0 unless defined($a);
$b = 0 unless defined($b);
my $total = $a + $b;

The reality is even more messy, since more than two variables are concerned.

What I really want to write is this:

my $total = $some_href->{$code}{'A'} + $some_href->{$code}{'B'};

and have undef correctly evaluate to 0 but I get these warnings in almost every run:

Use of uninitialized value in addition (+) at Stats.pm line 192.

What's the best way to make these messages go away?

NB: I 'use strict' and 'use warnings' if that s relevant.

like image 306
Anon Gordon Avatar asked Aug 29 '09 10:08

Anon Gordon


People also ask

How to undefine a variable in Perl?

undef() function: undef is used to reset the value of any variable. It can be used with or without the parentheses. It means that parentheses are optional while using this function.


1 Answers

It's good that you're using strict and warnings. The purpose of warnings is to alert you when Perl sees behavior that's likely to be unintentional (and thus incorrect). When you're doing it deliberately, it's perfectly fine to disable the warning locally. undef is treated as 0 in numeric contexts. If you're okay with both having undefined values and having them evaluate to zero, just disable the warning:

my $total;
{
  no warnings 'uninitialized';
  $total = $some_href->{$code}{A} + $some_href->{$code}{B};
}

Note: Disable only the warnings you need to, and do so in the smallest scope possible.

If you're averse to disabling warnings, there are other options. As of Perl 5.10 you can use the // (defined-or) operator to set default values. Prior to that people often use the || (logical-or), but that can do the Wrong Thing for values that evaluate to false. The robust way to default values in pre-5.10 versions of Perl is to check if they're defined.

$x = $y // 42;             # 5.10+
$x = $y || 42;             # < 5.10 (fragile)
$x = defined $y ? $y : 42; # < 5.10 (robust)
like image 103
Michael Carman Avatar answered Sep 28 '22 05:09

Michael Carman