in reply to check if an element exists in array

If all you want to do is check if the name is in the list then a hash is the way to go. But, to search an AoA, you could use grep:
my @names = ( [ qw/Jim 12/ ], [ qw/John 15/ ], [ qw/Peter 08/ ], [ qw/Andrew 34/ ], [ qw/Jim 57/ ], [ qw/Andreas 27/ ], ); my $name = 'Jim'; #simple searching if ( grep { $_->[0] eq $name } @names ) { print "$name\'s in the list\n"; } # or to get all of $name's entries for ( grep { $_->[0] eq $name } @names ) { print "@$_\n"; }

Output:

Jim's in the list Jim 12 Jim 57


Unless I state otherwise, my code all runs with strict and warnings

Replies are listed 'Best First'.
Re^2: check if an element exists in array
by Anonymous Monk on Apr 19, 2008 at 09:13 UTC
    I wanted to use a hash, but how will I build it? I do not have unique names...
      Using @names as before...
      my %names_h = map { $_->[0] => 1 } @names; # map { @$_ } @names; # similar, but more scary my $name = 'Jim'; print "Jim's in the hash\n" if $names_h{$name};


      Unless I state otherwise, my code all runs with strict and warnings
        Thank you all, I seem to be close...
        But if I go with grep as you suggest, I DO find the names, but how do I print the numbers as well? I tried with $_->1 but didn't work...