in reply to Howto strip 42 from comma separated list using s///

I'd look for commas on both sides and only replace one of them if they were both there:
# updated, thanks to PerlMouse -- not using \b, though! $str =~ s/(^|,)42(,|$)/$1 && $2/e

Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

Replies are listed 'Best First'.
Re^2: Howto strip 42 from comma separated list using s///
by Perl Mouse (Chaplain) on Nov 03, 2005 at 13:42 UTC
    You ought to guard the 42 with \b's on both sides, or it will turn 130,1423,999 into 130,13,999.
    Perl --((8:>*
Re^2: Howto strip 42 from comma separated list using s///
by svenXY (Deacon) on Nov 03, 2005 at 13:34 UTC
    Hi,
    sorry, but just for me to understand:
    $1 && $2
    means: if both are there, return the latest, in this case $2?
    Like this:
    perl -e'$a=1;$b=2;print ($a && $b)'
    Thanks,
    svenXY
      It's a trick, I'll admit. In Perl, && returns the right-hand operand if the left-hand one is true, and the left-hand operand if the left-hand one is false. X && Y returns X if X is false, and Y if X is true (regardless of Y's truth value!).

      Thus, in my regex, a comma is only inserted if both $1 and $2 are true. $1 && $2 is only true when $1 and $2 have commas in them (otherwise, at least one of them is empty, and thus the empty string is returned).


      Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
      How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re^2: Howto strip 42 from comma separated list using s///
by ady (Deacon) on Nov 03, 2005 at 13:39 UTC
    I'm currently doing this in .NET C# (which you couldn't know), where i can't eval like that, so a regex substitution /$1$2/ would eat both commas, like
    "41,42,43" -> "4143"
    Any plain vanilla regex to do it ?
    /allan