Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

TeeJay (2309)

  (email not shown publicly)

Working in Truro
Graduate with BSc (Hons) in Computer Systems and Networks
pm :,,
lug : Devon & Cornwall LUG
irc : TeeJay
skype : hashbangperl
livejournal : hashbangperl []
flickr :hashbangperl []

Journal of TeeJay (2309)

Tuesday July 19, 2005
10:25 AM

good perl idiom equivilent to SQL's IN operator

[ #25789 ]
This afternoon I was changing some code that checked if a value matched one of a couple of values for each clause, but now it matches up to a dozen.

If it was SQL I'd use the nice IN operator, but perl lacks an equivilent. Will perl6 include a fast, efficient equivilent without resorting to the LISP/Scheme/CrackInspired syntax that I see so much of in the summaries?

Using perl 5 I abuse grep like so

   if (grep ($var == $_ , (3,4,6,8..11,12,14,15))) {
     print " matches\n";
   } else {
     print " has no matches\n"

Which I think is pretty readable if slower than a bunch of hand written == and & glued together across 6 lines.
or I could use the Number::Range module.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.
  • While I can't say I'm wild about the name -- though I can't think of a better one -- the List::MoreUtils [] module seems to offer a more general solution.

    use List::MoreUtils qw/any/;

    if (any {$var == $_ } 3,4,6,8..11,12,14,15) {
        print " matches\n";
    } else {
        print " has no matches\n"
    • I don’t see how that makes anything any better. You can s/any/grep/ and remove the use line and that works.
      • Because if you have a large list, grep forces you to iterate over every element. That could be expensive if called many times. any is easy to read and terminates as soon as any element in the list meets the condition. Of course, that still doesn't mean that any is better, but if you're using that in conjunction with other functions in that module, it can be a win.

        • Well, yes. And I did consider that.

          But it really only matters if you have a large list in which you look for some values much more frequently than for others, so reordering the list can yield consistent savings. Otherwise you’re just reducing the runtime from n steps to n/2 averaged steps – both of which are O(n).

          If that tiny an optimization actually manages to make a noticable difference, then you really have no excuse not to use a hash.

          If the code block was doing something much more comp

  • In p5, you could use Quantum::Superpositions any()

    In p6, they are called junctions - and in this case it is still any()