运输手续费CGI/Perl

oxiaedzo  于 2023-01-17  发布在  Perl
关注(0)|答案(2)|浏览(158)

我想添加阿拉斯加(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);
sqxo8psd

sqxo8psd1#

不能像这样对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 }

那些弯弯曲曲的如果森林足以让人头晕目眩,而且大部分都是不需要的,如果一个值不小于等于24. 99,那么它一定大于24. 99,所以不需要再检查了。

cunj1qz1

cunj1qz12#

这段代码完全是一团糟,有多个语法错误,并且违反了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;
}

相关问题