On Aug 15, Scott R. Godin said:

quantity        1 - 9           0%
quantity        10 - 19         25%
quantity        20 - 199        40%
quantity        200 - 499       50%
quantity        500+            55%

I'd like to read it in via a __DATA__ handle, and perform the discount
calculation based on the total # of items (out of 6 individual items, each priced differently but contributing to the total quantity towards the discount percentage).

what are some perlish ways one would go about performing this calculation efficiently ?

Well, if the quantities are going to be relatively small numbers, you could use an array:

  my @discount;

  while (<DATA>) {
    if (my ($lower, $upper, $disc) = / (\d+) - (\d+) +(\d+)%/) {
      @discount[$lower..$upper] = ($disc) x ($upper - $lower + 1);
    }
    elsif (my ($lower, $disc) = / (\d+)\+ +(\d+)%/) {
      $discount[$lower] = $disc;
    }
    else {
      warn "unsupported discount line (#$.): $_";
    }
  }

Then you would simply poll @discount to find out the rate; this is assuming $quantity is some positive number:

  my $rate = ($discount[$quantity] || $discount[-1]) / 100;

If there is no entry for $discount[$quantity], that means it's greater than 500 (in your sample case), thus it gets the same discount as 500 items. Since $discount[500] is the last element in @discount, it's the same as $discount[-1].

--
Jeff "japhy" Pinyan         %  How can we ever be the sold short or
RPI Acacia Brother #734     %  the cheated, we who for every service
http://japhy.perlmonk.org/  %  have long ago been overpaid?
http://www.perlmonks.org/   %    -- Meister Eckhart

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to