in reply to how to quickly tell if number is in an array

The methods shown so far are best if the test only occurs a few times in the program and if the list is short. For frequent use, make a hash with the array elements as keys, and check for existence of the test value as a key.

my @array = (1,2,5..20,42..99); my %element; @element{@array} = (); print exists $element{$num}? "$num found": "$num not found";

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: how to quickly tell if number is in an array
by sauoq (Abbot) on Oct 13, 2005 at 01:26 UTC
    For frequent use, make a hash

    Yes. (But don't do this with refs.) There are compromises too, like binary searches and Tie::IxHash and other modules. Lots of different trade-offs can be made between ordering restrictions, code complexity, execution time, and space requirements. The trick is picking the right one. :-)

    -sauoq
    "My two cents aren't worth a dime.";