You did not state in what circumstances exists is not good enough for you, so in the spirit of TIMTOWTDI I present a reimplementation that might be faster. You might want to use Benchmark to find out the relative performance gain. The function implements the sort reverse keys mechanism, which is why I call it exists_srk.
%x = (foo=>1,bar=>2,baz=>3);
sub exists_srk(\%$){my($h,$k)=@_; map{$_ eq $k?$_:()}(sort reverse key
+s %$h)};
print exists_srk(%x,$_) for qw(foo bar baz bat)
Of course, since you don't tell us anything, it's hard to come up with an optimization for your special case. But if you don't know anything about how exists works, it's hard to tell you anything other than to learn how exists works before looking for a replacement.
Update: After some discussion in the CB, there came up another method which you should benchmark as well. I call it exists_ggg because it uses grep three times. It relies on the fact that grep steps through the list in order though, so it might not work on a platform where the sequence of items visited by grep is different from the current Perl implementation.
sub exists_ggg (\%$) {
my($h,$k) = @_;
my $c;
grep { len == len $k }
grep /^\Q$k\E/
grep { $c++ == 0 } %$h
};
Update2: If the documentation and the code differ, at least one of them is wrong. In this case, the last map should have been a grep as well. Thanks blazar. |