First, welcome to the Perl community. I hope you get as much enjoyment out of working with Perl as I have.

Your regular expression misses the case where either the first or last element of your list is the element you wish to check for. Consider:

#!/usr/bin/perl use strict; use warnings; my $csv = 'value1,value2,value3'; my $value = 'value1'; if ($csv =~ /(?:^|,)$value(?:,|$)/) { print "Yes\n"; } else { print "No\n"; } if ($csv =~ /[,]$value[,]/) { print "Yes\n"; } else { print "No\n"; }

Mine catches those cases since the first group ((?: ... )) matches on either the start of the string (^) or a comma and the second group matches on either the end of the string ($) or a comma. Since value1 is not surrounded by commas, yours will not find it. Note that both cases will fail if there is white space in the csv that is not in the $value.

You might also note there is no need to define the single-element character class [,] as opposed to just using the raw comma ,.

As a side note, please read Markup in the Monastery, since by not wrapping your code in code tags, you inadvertently converted [,] into a link - when this happens, monks frequently misread your intention.


In reply to Re^3: reg exp to find presence of value in a list of comma seperated list by kennethk
in thread reg exp to find presence of value in a list of comma seperated list by kgforperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.