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

EDIT: Version updated below in another post to avoid full scan.
Hi Ppeoc :)

use strict; use warnings; my @arr = qw(Apple Banana Tiger Lion Cat Turtle); my $flag1 = (grep { /Apple|Turtle/ } @arr) ? 1 : 0; my $flag2 = (grep { /Lion|Tiger/ } @arr) ? 1 : 0; print "flag1:$flag1 flag2:$flag2\n";

Edit: why do you give me a bad reputation?
This code is working and better than the original!
  • Comment on Re: The most efficient way for searching for an element in an array?
  • Download Code

Replies are listed 'Best First'.
Re^2: The most efficient way for searching for an element in an array?
by choroba (Cardinal) on Jan 08, 2016 at 00:02 UTC
    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,
      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.
      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.