in reply to searching an array

A hash is handy for these type of jobs.

#!/usr/bin/perl use strict; use warnings; my @array = (qw(peter paul john mary)); my $name = 'jim'; my %lookup = map { $_ => undef} @array; die "$name not found\n" unless exists $lookup{$name}; print "found $name\n";

Replies are listed 'Best First'.
Re^2: searching an array
by Articuno (Beadle) on Jan 03, 2006 at 15:45 UTC
    I prefer
    my @lookup{@array} = undef;
    to (*)
    my %lookup = map { $_ => undef } @array;
    :-)

    (*) should it be "to" or "instead of" ?

    -- 6x9=42
      Except that's a syntax error. You can't declare a hash slice. You'd have to declare the hash, then do the slice-assignment.

      Caution: Contents may have been coded under pressure.
        Oh, ok... I need more sleep... :-)

        -- 6x9=42
Re^2: searching an array
by holli (Abbot) on Jan 03, 2006 at 18:26 UTC
    This is really up to the problem.

    If your problem demands one (or few) lookups you are better off scanning through the array, esp. if the array is huge or memory is short. If The array is sorted you can optimize this using a binary search algorithm.
    If you have many lookups and you can easily pay the price of memory, then the hash solution is appropriate.


    holli, /regexed monk/