Thread: Simple question

    #1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2000
    Posts
    4
    Rep Power
    0
    How to determine if a value is already in an array?

    Of course I can do it with a loop and compare, but I suspect there must be easier ways. (forgive me, I am a perl rookie).

    Thanks in advance.
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2000
    Posts
    11
    Rep Power
    0
    See the grep function:
    http://www.perldoc.com/f?grep

    @matches = grep { /this_pattern_from/ } @values

    Sample usage:

    my @ary = qw(one two three);
    my $val = 'test';

    if (grep { /$val/ } @ary) {
    print "it existsn";
    }
    else {
    print "it does not existn";
    }


    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">quote:</font><HR>Originally posted by liupang:
    How to determine if a value is already in an array?

    Of course I can do it with a loop and compare, but I suspect there must be easier ways. (forgive me, I am a perl rookie).

    Thanks in advance.
    [/quote]

  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2000
    Posts
    0
    Rep Power
    0
    I think simplest way is to use hashes :
    @a = qw {one two three};
    $var = 'test';

    @seen{@a}=1;
    print "$var already exists" if $seen{$var};


    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">quote:</font><HR>Originally posted by liupang:
    How to determine if a value is already in an array?

    Of course I can do it with a loop and compare, but I suspect there must be easier ways. (forgive me, I am a perl rookie).

    Thanks in advance.
    [/quote]



    ------------------
    Regards, Andrew
    ==================
    http://afixxer.boom.ru

IMN logo majestic logo threadwatch logo seochat tools logo