in reply to Checking for occurrence in comma separated string

You could turn the string into an array, using split, and then use grep to check existence of an item. (Or use a hash as a set if you need to test this one list a lot.)
my @list = split /,/, $thestring; if(grep { $_ == $thecheck } @list) { print "Found it!\n"; } # Or, if you need this a lot: # preparation: my %set; $set{$_} = 1 foreach split /,/, $thestring; # actual test: if($set{$thecheck}) { print "Found it!\n"; }

If you do insist on using a regular expression, you need to be aware that a number can appear at the beginning or at the end of a string. Example check:

if($thestring =~ /(?:^|,)$thecheck(?=,|$)/) { ... }
but I prefer the double negative:
if($thestring =~ /(?<![^,])$thecheck(?![^,])/) { ... }
(If there's anything in front or right after the match, it may not be anything other than a comma.)

Replies are listed 'Best First'.
Re^2: Checking for occurrence in comma separated string
by Delusional (Beadle) on Oct 25, 2005 at 11:16 UTC
    Thanks Bart, I think your right. I was hoping on a simple if compairson method without using arrays etc, but it appears that the array method is the method I should be using for this.

    Thanks...
      You can also prepend and append a comma to your strings, and use index to quickly search for it. It may likely be faster than a dynamically built regexp.
      if(index(",$thestring,", ",$thecheck,") >= 0) { ... }
      That will search for ",13," inside the string ",13,130,213,".