にキーを割り当てることができます
use strict;
use warnings;
my %size = (Regular => "6",
Large => "8",
Family => "11",
);
print $size{Large};
、あなたはなかれあなたのコード内でuse strict
とuse warnings
を含める必要があります。それはあなたの問題のいくつかを指摘するでしょう。
あなたのコードを見てみましょう。あなたはトッピングの数を取得するために$toppings
の代わり@toppings
を使用
- :
# 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');
だから、あなたは、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');
「動作しない」...どのように?具体的にする。単一引用符は変数の補間を防ぎます。 'print(" Total due:$ total ");' – toolic
'use strict;を必ず使用してください。警告を使う; '! '$ toppings'という名前の変数を使用しますが、そのような変数に値を割り当てない(宣言または)ことはできません。 – ikegami
また、 '%size'が使用されていないという事実は、第2の問題が存在することを示唆しています。 – ikegami