in reply to optimization - exists should return a reference

I like the idea a lot. Performance, although not to be neglected when thinking about how a feature will affect the average case, is not so much motivation to me as the fact that this provides a clean way to do it Once And Only Once. Right now, there is no way to achieve that for exists tests. For multilevel lookups you can roll up the lookup for most of the path which gets close, but no cigar:
exists $_->{$client} and return $_->{$client} for $export_def->{'..client_default_version'};
But there's just no way around the duplicate mention of $client. And just as I was typing this code, I forgot the sigil in the second lookup and only by chance caught it a few seconds before submitting, which demonstrates why Once And Only Once is a good idea. Had I made this mistake in actual code, it would have broken silently and possibly left me to scratch my head for a long time.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re: optimization - exists should return a reference
by Abigail-II (Bishop) on Jan 15, 2003 at 09:32 UTC
    Ah, but you don't avoid the 'once-and-only-once' with the modified exists either. You'd have to write something like:
    do {my $tmp = $_ -> {$client}; return $$tmp if $tmp;} for $export_def->{'..client_default_ver +sion'};

    But then you have $tmp three times. And you can still leave the sigil off of $client and have strangely behaving code.

    Abigail

      do {my $tmp = $_ -> {$client}; return $$tmp if $tmp;} for $export_def->{'..client_default_version +'};
      I don't see any use of this proposed new exists (or any existance test at all for that matter) there. What are you trying to show? As BrowserUk said what I'd write then would be
      return $$_ if $_ = exists $export_def->{'..client_default_version'}{$client};
      For the purpose of demonstration, you can even avoid assignments altogether:
      { return ${ exists $export_def->{'..client_default_version'}{$client} or last } }

      Yes, if I forget the sigil on $client I'll still get strange results, but having to get it right twice still offers more room for failure, not to mention the fact that if I get the sole instance of it wrong I will get consistent rather than intermittent failure which is far easier to notice and track.

      I stand by my point, this proposition is A Good Thing in terms of promotion of good programming practices.

      Makeshifts last the longest.

      Surely

      exists $_->{$client} and return $_->{$client} for $export_def->{'..client_default_version'};

      Would just become

      return $$_ if $_ = exists $export_def{'..client_default_version'}{$cli +ent};

      Which gives the desired once-and-once-only behaviour?


      Examine what is said, not who speaks.

      The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.