2016-10-26 26 views
-3

我寫了一個程序,允許用戶選擇產品的大小,並將大小放在哈希數組中。但是,當我嘗試編寫列出所有澆頭的部分(用戶可以選擇多個澆頭但只有1個尺寸)時,我的公式不起作用。這個Perl CGI程序爲什麼不計算哈希數組中的項目?

my %size = ('Regular' => 6.00, 
     'Large' => 8.00, 
     'Family' => 11.00); 

my $size = param('size'); 

my @toppings = param('toppings'); 

my $total_topping = $toppings * 1.25; 
my $total = $size + $total_topping; 
print ('Total Due: $total'); 
+1

「不工作」 ......在什麼樣的方式?請明確點。單引號防止可變插值;使用雙引號:'print(「Total Due:$ total」);' – toolic

+4

始終使用'use strict;使用警告;'!你使用了一個名爲'$ toppings'的變量,但是你從來沒有(聲明或)爲這個變量賦值。 – ikegami

+4

此外,'%size'沒有被使用的事實表明存在第二個問題。 – ikegami

回答

0

正如其他都提到一個數組,你應該送花兒給人包括在你的代碼use strictuse warnings。這會指出你的一些問題。

讓我們來看看你的代碼。

# This defines a hash mapping sizes of pizza to price 
my %size = ('Regular' => 6.00, 
     'Large' => 8.00, 
     'Family' => 11.00); 

# And this gets the size parameter from the user's request. 
# Presumably, this value should be one of the keys from the %size hash. 
my $size = param('size'); 

# This gets an array of all of the toppings the user has selected. 
my @toppings = param('toppings'); 

# Each topping adds £1.25 to the price, so to get the total price 
# for toppings, we need to multiply the number of toppings by 1.25. 
# But that's not what you're doing here. You're using a new scalar 
# variable called $toppings. This will be undef and will therefore 
# be interpreted as zero. 
# This problem would have been picked up by "use strict" 
my $total_topping = $toppings * 1.25; 

# And here you're adding $size to $total_toppings to get the 
# total price of the pizza. But $size doesn't contain the price, 
# it contains the description of the size. Any of your sizes will 
# be interpreted as 0 when used as a number. So $total will end 
# up as 0 + 0 = 0. 
# This problem would have been picked up by "use warnings". 
my $total = $size + $total_topping; 
print ('Total Due: $total'); 

所以,你有兩個錯誤:

  1. 您使用$toppings代替@toppings拿到配料的數量。
  2. 忘了將尺寸名稱翻譯爲尺寸價格。

您的代碼應該看起來更像是這樣的:

my %size = (Regular => 6.00, 
      Large => 8.00, 
      Family => 11.00); 

my $size = param{'size'); 
# Check for valid size 
if (! exists $size{$size}) { 
    die "$size is not a valid size of pizza"; 
} 
# Convert name of size to cost of size. 
my $size_cost = $size{$size}; 

my @toppings = param('toppings'); 

# Array in scalar context gives number of elements 
my $total_toppings = @toppings * 1.25; 

my $total = $size_cost + $total_topping; 
print ('Total Due: $total'); 
0

您定義了一個散列​​3210但從來沒有使用它? $澆頭的價值在哪裏?

無論如何,這裏看到的是一種顯示鍵'大'的值的方法,只是爲了給出一個關於如何使用散列的想法。

use strict; 
use warnings; 

my %size = (Regular => "6", 
      Large => "8", 
      Family => "11", 
      ); 

print $size{Large}; 

您也可以指定鍵

my @Sizes = keys %size;