A Perl array 'contains' example

Perl array FAQ: How can I test to see if a Perl array already contains a given value? (Also written as, How do I search an array with the Perl grep function?)

I use the Perl grep function to see if a Perl array contains a given entry. For instance, in this Perl code:

if ( grep { $_ eq $clientAddress} @ip_addresses )
{
  # the array already contains this ip address; skip it this time
  next;
}
else
{
  # the array does not yet contain this ip address; add it
  push @ip_addresses, $clientAddress;
}

I'm testing to see if the Perl array "@ip_addresses" contains an entry given by the variable "$clientAddress".

Just use this Perl array search technique in an "if" clause, as shown, and then add whatever logic you want within your if and else statements. In this case, if the current IP address is not already in the array, I add it to the array in the "else" clause, but of course your logic will be unique.

An easier "Perl array contains" example

If it's easier to read without a variable in there, here's another example of this "Perl array contains" code:

if ( grep { $_ eq '192.168.1.100'} @ip_addresses )

if you'd like more details, I didn't realize it, but I have another good example out here in my "Perl grep array tutorial." (It's pretty bad when you can't find things on your own website.)