in reply to Re: The most efficient way for searching for an element in an array?
in thread The most efficient way for searching for an element in an array?

why do you give me a bad reputation?
I don't know (I haven't downvoted the post). Nevertheless, I see some issues:
  1. /Cat|Turtle/ would match Catalogue as well.
  2. grep examines all the elements of the array, even if it finds a match at the very beginning. That's probably not "the most efficient way".
($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^3: The most efficient way for searching for an element in an array?
by hotchiwawa (Scribe) on Jan 08, 2016 at 09:04 UTC
    choroba :)

    1) yep it's OR condition. 2) yep full scan not perfect but not returned. Maybe there is an operator to quit the grep... I will check
      2) No you cannot break map grep sort just because they are not loops!

      L*
      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
        in fact there is a loop (in sort, map, grep) but no internal checks to escape like single match...
Re^3: The most efficient way for searching for an element in an array?
by hotchiwawa (Scribe) on Jan 08, 2016 at 09:34 UTC
    A new version :)
    use strict; use warnings; my @arr = qw(Apple Banana Tiger Lion Cat Turtle); my $arr = join("|", @arr); my $flag1 = ($arr =~ m/Apple|Turtle/) ? 1 : 0; my $flag2 = ($arr =~ m/Lion|Tiger/) ? 1 : 0; print "flag1:$flag1 flag2:$flag2\n"; $arr = undef; #you can release the array too undef @arr;

    Now there is no more full scan when a match is encountered.

    Peace
      my @arr = qw(Apple Banana Tiger Lion Cat Turtle); my $arr = join("|", @arr); my $flag1 = ($arr =~ m/Apple|Turtle/) ? 1 : 0;

      That breaks as soon as the elements of @arr may contain the string used to join the arrays. Also, it roughly doubles the memory usage. Imagine a 2 GByte @arr on a machine with 4 GByte RAM.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
      A reply falls below the community's threshold of quality. You may see it by logging in.