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

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

Thread Previous | Thread Next
Aaron Priven
July 5, 2012 23:15
Re: Smartmatch two cents (was... List::Util... when...)
Message ID:
On Jul 5, 2012, at 7:47 PM, Ricardo Signes wrote:

> * Ed Avis <> [2012-07-03T04:59:34]
>> As in Python, 'in' could work for both arrays and hashes:
>>   $x in @array
>>   $x in %hash    # same as exists $hash{$x}
> Alas, Perl is not Python, and alas, Python is not Perl.  The "in" operator in
> Python works nicely because Python's type system is different to Perl's.
> We're not going to be adding an `in` operator, because it goes against the
> idea of where Perl decides what type to use.  Fortunately, Perl6::Junction and
> other libraries provide excellent tools for doing this kind of scanning.  I use
> them all the time and don't regret it for a second.


I can understand how an "in" operator might have typing issues, especially if, as above, it works "for both arrays and hashes" (which means that it doesn't just flatten the hash into a list). I didn't realize that until I sat down and thought about what you wrote here.

But at its simplest, an "in" operator could be a shorter, faster, infix version of this:

sub in {
   my $member = shift; 
   for (@_) {
      return 1 if $member eq $_;
   return q{};

Except for the use of "eq", it doesn't assume anything about the type of anything. And inferring numeric / string from the operator is what, I thought, Perl did. Hence the suggestion of a numeric "in" operator.

That's not to say it's necessarily worth doing. Maybe, as Aaron Crane suggests, it's not "powerful enough to justify its own existence." 

I personally think "$x in (list)" is clearer and easier to understand than  the alternatives -- $x eq any((list));  List::MoreUtils::any {our $_; $_ eq $member} (list); copying and pasting the loop each time; or, for that matter, using "in" as a regular sub. And I do use "$x ~~ @list" somewhat frequently, so to me it would be nice to have a simple and equivalent replacement without the ambiguity of smartmatch.

That's just my opinion, and not worth much, of course.

But it is possible to separate the idea of the in operator from the problematic assumptions about types that come from smartmatch, or from treating Perl like Python, and consider "in" on its own merits.
Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About