题
我在这种形式的片段:
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;
,因为多于两个变量都在关注现实的情况是更杂乱,
我真正想写的是这样的:
my $total = $some_href->{$code}{'A'} + $some_href->{$code}{'B'};
和民主基金有正确评价为0,但我几乎在每次运行得到这些警告:
Use of uninitialized value in addition (+) at Stats.pm line 192.
什么是使这些消息走开的最好方式?
NB:I '使用严格的' 和 '使用的警告' 如果是s相关
。解决方案
这是很好的,你使用strict
和warnings
。警告的目的是当看到Perl的行为很可能是无意的(因而不正确的)来提醒你。当你故意做的,这是完全正常的在本地禁用警告。 undef
被视为在数字环境0
。如果你没事既具有未定义的值,并让他们评估为零,只是禁用警告:
my $total;
{
no warnings 'uninitialized';
$total = $some_href->{$code}{A} + $some_href->{$code}{B};
}
请注意:仅禁用你需要的警告,并在最小的范围内这样做可能
如果你反对禁用的警告,还有其他的选择。像Perl 5.10你可以使用//
的(定义-OR)操作员设置的默认值。在此之前,人们经常使用的||
(逻辑或),但可以用于计算结果为假值做错事。坚固的方式为默认的预5.10版本的Perl的值是检查,如果他们defined
。
$x = $y // 42; # 5.10+
$x = $y || 42; # < 5.10 (fragile)
$x = defined $y ? $y : 42; # < 5.10 (robust)
其他提示
可以关闭“未初始化的”警告用于第二:
my $a;
my $b = 1;
{
no warnings 'uninitialized';
my $c = $a+$b; # no warning
}
my $c = $a+$b; # warning
或者可以短路到零:
my $d = ($a||0)+$b; # no warning
不看对我很好,虽然。
作为要添加它们,只需过滤掉undefs。
use List::Util 'sum';
my $total = sum (0, grep {defined} $some_href->{$code}{'A'}, $some_href->{$code}{'B'});
或者甚至
use List::Util 'sum';
my $total = sum (0, grep {defined} map {$some_href->{$code}{$_}} 'A', 'B');
my $a = $some_href->{$code}{'A'} || 0;
my $b = $some_href->{$code}{'B'} || 0;
my $total = $a + $b;
在这种情况下,这是确定治疗,因为你的回退值的相同不定值假值。
不隶属于 StackOverflow