Building a Pizza: Calculating Cost
June 14, 1999
sub calcTotal()
#calculate pizza cost based on current parameters
{ %sizelabels=('small'=>'small (8",$5)',
'medium'=>'medium (12",$8)',
'large'=>'large (16",$10)',
'xlarge'=>'x-large (18",$12)');
%sizeprices=('small'=>5,
'medium'=>8,
'large'=>10,
'xlarge'=>12);
%toppingsprices=('small'=>.50,
'medium'=>.75,
'large'=>1.00,
'xlarge'=>1.25);
$baseCost=$sizeprices{$size};
@allToppings=$cgiobject->param("order_toppings");
$toppingsCost=($#allToppings+1)*($toppingsprices{$size});
return $baseCost+$toppingsCost;
}
The calcTotal subroutine evaluates the values
of the relevant form fields, as submitted, and calculates
a price. First, three hashes are setup. The first hash,
%sizelabels, will actually be used in the
output_form subroutine to create the labels
for the radio button group field which selects the
pizza size. We've put this hash
assignment here, though, because it contains price
information, and in case the prices need to be updated it is
easier with them all in one place.
The two other hashes, %sizeprices and
%toppingsprices, relate dollar figures with
pizza size values.
These values are also used in the pizza size radio
button group. Thus, pizza size "small" is keyed to
a value of 5 in the %sizeprices hash and a
value of .5 in the %toppingsprices hash. These are the
base prices for the pizza and the topping, respectively.
Next we calculate the base cost of the pizza given
its size, contained in the variable $size. Next we
count up the number of toppings by creating an array,
@allToppings, which takes a list of all toppings submitted
through the parameter order_toppings. The construct
$#allToppings represents the highest index in
the array, so if this value were zero that means there
is one topping in the list. Thus, we add one to this value
and multiply by the cost of toppings for a pizza of the
given size. Whew!
In the end, we can simply add together the
$baseCost and the $toppingsCost, which is returned
from this subroutine as the total price of the pizza, as
outfitted.
Building a Pizza: Taking the Order
The Perl You Need to Know
Building a Pizza: Completing the Order
|