我想为阿拉斯加(AK)和夏威夷(HI)增加25美元的手续费 - 当我将状态和固定费用添加到下面的运输矩阵时,我的测试中断了。有人能指出我正确的方向吗?
my $totalPounds = sprintf("%.2f",($totalWeight / 16));
#my $shipping = &getShipUPS($totalPounds, $zip, $shipType);
if ($subtotal <= 24.99) {$shipping = '10.95';}
elsif (($subtotal > 24.99) && ($subtotal <= 74.99)) {$shipping = '13.95';}
elsif (($subtotal > 74.99) && ($subtotal <= 149.99)) {$shipping = '14.95';}
elsif ($subtotal >= $150) {$shipping = '18.95';}
elsif ($state eq 'HI','AK') ($subtotal <= 24.99) {$shipping = '10.95'+'25.00';}
elsif ($state eq 'HI','AK') (($subtotal > 24.99) && ($subtotal <= 74.99)) {$shipping = '13.95'+'25.00';}
elsif ($state eq 'HI','AK') (($subtotal > 74.99) && ($subtotal <= 149.99)) {$shipping = '14.95'+'25.00';}
elsif ($state eq 'HI','AK') ($subtotal >= $150) {$shipping = '18.95'+'25.00';}else
$shipping = sprintf("%.2f", $shipping);
my $total = $subtotal + $tax + $shipping;
$subtotal = sprintf("%.2f", $subtotal);
$total = sprintf("%.2f", $total);
答案 0 :(得分:2)
您不能使用eq
这样的多个参数
$state eq 'HI','AK'
你需要做
$state eq 'HI' or $state eq 'AK'
另外,你不能在elsif
这之后的第一个
elsif ($state eq 'HI','AK') ($subtotal >= $150)
你需要做
elsif ( ($state eq 'HI' or $state eq 'AK') or ($subtotal >= $150) )
# ^---- main parantheses -------^
当然,更明智的选择可能是使用哈希
%extra_charges = ( AK => 25,
HI => 25,
# etc
);
...
$subtotal += $extra_charges{$state}; # assuming no missing states
if-else逻辑也是各种冗余。这应该等同于你的代码:
if ($subtotal <= 24.99) { $shipping = '10.95' }
elsif ($subtotal <= 74.99) { $shipping = '13.95' }
elsif ($subtotal <= 149.99) { $shipping = '14.95' }
else { $shipping = '18.95' }
if ($state eq 'AK' or $state eq 'HI') { $shipping += 25 }
那些蜿蜒的ifs森林足以让人晕眩,其中大多数都不是必需的。如果值不小于或等于24.99,则必须大于24.99,因此无需仔细检查。
答案 1 :(得分:1)
该代码完全混乱,有多个语法错误,并且违反了DRY。
最好先计算基本运费,具体取决于小计。如果州是夏威夷州或阿拉斯加州,您可以在第二步中添加25美元的费用:
my @shipping_fees = (
# max subtotal => fee
[ 24.99 => 10.95 ],
[ 74.99 => 13.95 ],
[ 149.99 => 14.95 ],
[ inf => 18.95 ],
);
my %extra_fees_per_state = (
AK => 25.00,
HI => 25.00,
);
然后:
my $shipping;
for my $shipping_fee (@shipping_fees) {
my ($max, $fee) = @$shipping_fee;
if ($subtotal <= $max) {
$shipping = $fee;
last;
}
}
if (defined( my $extra = $extra_fees_per_state{$state})) {
$shipping += $extra;
}