On Monday, March 31, 2003, at 10:15 AM, Jonathan Scott Duff wrote:


On Mon, Mar 31, 2003 at 10:09:43AM -0800, Michael Lazzaro wrote:
I'm still hoping rather desperately for a if-uninitialized op in
general, even if only for hashes, because the difference between
"present but undefined" and "not present" is rather crucial for some
common algorithms.

Can you give some examples?

Sure, edited slightly from my last mail...


I suppose my own most common example is a hash representing a cache... it's entirely possible for C<undef> to be calculated and cached, but that doesn't mean the cache entry is invalid and should be recalculated every time -- a nonextant key would mean the cache entry is invalid.

  {
    $cache.{ $key } = &foo($key)        # (1)
        if not exists $cache.{ $key };
    $cache.{ $key };
  }

In my own experiences, code similar to the above is awfully common. An assign-if-not-present form (at least for hashes, but in a magical fairy world, for arrays/params/whatever, too) such as:

$cache.{ $key } ///= &foo($key); # (2)

would be a lot cleaner, and maybe a little faster, since it's testing C<$cache.{ $key }> once instead of -- what, 2.5 or 3 times, I guess, depending on how you count it?

There are other examples -- working with external data sources, primarily -- but they pretty much always boil down to the same general concept. I basically want the shortest, *fastest* possible way to say the caching code above given above.


MikeL



Reply via email to