in reply to Re^2: 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?

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
  • Comment on Re^3: The most efficient way for searching for an element in an array?
  • Download Code

Replies are listed 'Best First'.
Re^4: The most efficient way for searching for an element in an array?
by afoken (Chancellor) on Jan 08, 2016 at 19:54 UTC
    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.