Check if a variable is NOT in an array?


Any one know how to check if the variable $field is NOT in the array @Sort?

well the easiest way would be to loop the array. You might want to sort it to properly match the data you’re comparing.

Or you could turn the array into a string and then do a regex. that might work. You should be able to just do:

my $values = join "," @sort;
if($values =~ m!$vartocheck!) {
   return 1;
return 0;

That should work. Although the join bit might be a little off, i very rarely use it. But i think that might be the fastest way.

Read the page I linked to above. Your suggestion will be slow and will return false matches as it also checks for substrings. return() also only works in a subroutine.

ah ok.

I’ll have a read. I thought it might have been good enough.

Anyone who can understand that probably wouldn’t be asking. :lol:

Yah, a hash is probably best, which is how I do it now, but for a long
time I just used grep:

$found = grep(/$field/, @SORT);

$found will return the number of times the regex was found in @SORT.

This is not a perfect method. If $field contains special characters you might get odd results.


He was not the person that asked the question. You can do it however you want, there is no one-size-fits-all answer. There are several suggestion on the page I linked to, maybe you could benefit from reading it as well.