develooper Front page | perl.perl5.porters | Postings from July 2012

Re: Smartmatch two cents (was... List::Util... when...)

Thread Previous | Thread Next
Aaron Crane
July 3, 2012 10:34
Re: Smartmatch two cents (was... List::Util... when...)
Message ID:
Ed Avis <> wrote:
> David Mertens asked:
>>Why would "$a in %hash" be equivalent to "exists $hash{$a}"?
> This is how it works in Python, and it seems natural in Perl too.

It doesn't seem particularly natural to me: I find it bletcherous
that, in Python, you can't statically tell the difference between an
O(1) dict-existence test and an O(N) sequence-containment test (let
alone a sequence-subsumption test).  Given that we already have a
perfectly cromulent operator for testing hash existence, and that the
existing builtins that DWIM between array refs and hash refs aren't
widely liked, I'm inclined to think that, if we acquire such an `in`
operator, it shouldn't allow a hash on its RHS.

Beyond that, I'm not at all convinced that this `in` is powerful
enough to justify its own existence (regardless of whether it
replicates the behaviour of `exists` on a hash).  If it can only do
string comparison, there are a variety of common tasks where you have
to write out a longhand equivalent anyway; if it guesses as to whether
you meant string equality or numeric equality or regex match or what
have you, then it repeats essentially all the problems of smartmatch
as currently implemented.

The more I consider this, the more strongly I think that a wordier API
is the right thing — along the lines of Test::Deep (now maintained by
our fearless pumpking) or Leon's Smart::Match.  I offer the following
anecdotal support for this position.  I currently have a codebase
which makes substantial use of List::MoreUtils::any and friends for
higher-order list-wise tests.  By my reckoning, only about one
occurrence in ten could be refactored to use an `in` operator of the
form you suggest; but every single occurrence can be refactored to use
Smart::Match (and almost all of them are made much clearer by doing

Aaron Crane **

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About