2013-06-26 90 views
0

我想爲阿拉斯加(AK)和夏威夷(HI)增加一個單位的25美元手續費 - 當我將狀態和固定費用添加到下面的運輸矩陣時,我的測試會中斷。有人能指引我朝着正確的方向嗎?裝運手續費CGI/Perl

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); 

回答

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,所以不需要再次檢查。

+0

感謝TLP我同意哈希將使更明智的選擇。現在測試。 – webdesignmichelle

+2

不要忘記使用'use strict;使用警告;'。 – TLP

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; 
} 
+0

Amon - 感謝您驗證代碼是一團糟...從另一個開發人員繼承。將修改和測試。 – webdesignmichelle