http://www.perlmonks.org?node_id=471770

in reply to alternatives to if and series of elsif

I prefer davidrw's map method, for this comparision, but in case anyone stumbles upon this and wants an alternative - you can use a hash instead:

```my (\$points, \$quota) = @_;
my %compare = (
18000 => 24,
16000 => 23,
14000 => 22,
... );
for my \$key (sort {\$b <=> \$a} keys %compare)
{
if (\$points > \$key and \$quota < \$compare{\$key})
{
return \$compare{key};
}
}
return 15;

Check out QM's reply for a better example

Update: it doesn't work for 16626 => 21, because it assumes the keys increment in conjuction with the values, which 16626 => 21 breaks. Added link.

"Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

Replies are listed 'Best First'.
Re^2: alternatives to if and series of elsif
by QM (Parson) on Jul 05, 2005 at 20:10 UTC
Why would you use a hash, and then do a linear search through the keys?

-QM
--
Quantum Mechanics: The dreams stuff is made of

You wouldn't :), I just used davido's as an example and, this looking suspiciously like homework my brother just got, left the exercise of creating a predefined hash to the OP (which would look much like your post anyway). I don't think kiat was asking for an answer to homework now, but didn't have time over the weekend to update. (and now that your post covers it I'll just leave it at a link to that.

"Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

Homework?!

All of this reminds me of trying to do the table-creation/lookup in Pascal (on proprietary equipment, so the language was chosen for me). I had to create index arrays for each dimension, and I had to make it generic enough so when a breakpoint changed, I only had to update one number (and the breakpoints changed daily). It was all a big mess of brackets and parens.

In fact, it was so ugly (even after max beautification), I felt I had to write a 2 paragraph explanation for the single line table population statement. And then added a "Don't touch this unless you know what you're doing. In fact, just don't touch it, because you don't know, and you don't need to."

I wonder if that code is still there?

-QM
--
Quantum Mechanics: The dreams stuff is made of