Your skill will accomplishwhat the force of many cannot PerlMonks

### Re^2: Perl Number range lookup question

by dsheroh (Prior)
 on Jun 18, 2012 at 14:21 UTC ( #976836=note: print w/replies, xml ) Need Help??

in reply to Re: Perl Number range lookup question
in thread Perl Number range lookup question

I'd definitely benchmark this vs. calculating the tier on the fly each time (i.e., in this case, run it against print int( ( \$x % 50 ) / 10 );). Especially with a simple tier calculation, I would expect the hash lookup to take longer than (re)calculating on demand.

Using the precalculated hash would also be slower if the number of lookups isn't substantially larger than the number of precalculated values. If fewer lookups would be done, but the calculation is slower than a hash lookup, the better option would be to do no precalculation and instead do your lookups with

```my \$tier = \$tiers{\$n} //= calculate_tier(\$n);
which will calculate the tier for a value the first time it's requested, then return the calculated value from the hash on subsequent requests for that value. (Note that you'll need to use ||= instead of //= if your perl is older than 5.10.)

Replies are listed 'Best First'.
Re^3: Perl Number range lookup question
by tobyink (Abbot) on Jun 18, 2012 at 17:34 UTC

```my \$tier = \$tiers{\$n} //= calculate_tier(\$n);

That's a rather elegant memoization technique for functions in general (provided the function parameters can't be references). If your function took two parameters, you could even do:

```my \$tier = \$tiers{\$n, \$m} //= calculate_tier(\$n, \$m);

... taking advantage of Perl's rarely used multi-dimensional array fakery.

perl -E'sub Monkey::do{say\$_,for@_,do{(\$monkey=[caller(0)]->[3])=~s{::}{ }and\$monkey}}"Monkey say"->Monkey::do'

Create A New User
Node Status?
node history
Node Type: note [id://976836]
help
Chatterbox?
 [mz2255]: I'm trying to post a question to "seekers of perl wisdom" but always getting a permission denied when I want to submit. There are no links in my post... [ambrus]: again? someone complained about this just a few days ago (although eventually they could post) [choroba]: Can you post the question in mz2255's scratchpad? [ambrus]: Corion, if you're here, can you check the spam filter logs to see what's triggering this time? [ambrus]: Petroza had trouble posting yesterday, but has posted Issues Fetching URL with a variable token since. [mz2255]: Yes, just edited the scratchpad. Not sure if I'm doing something wrong, it's my first time.

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (11)
As of 2017-10-19 15:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My fridge is mostly full of:

Results (255 votes). Check out past polls.

Notices?