Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have a dynamic output like this where the number of names and names themselves change but it always has a comma at the end: Jones, Smith, Baker, Johnson,

I would like to get rid of the last comma and make it like this: Jones, Smith, Baker, Johnson

My attempt to get rid of last comma:
s/$myNames,$/$myNames/;
I know the "$" matches the last character but not sure how to eliminate the ",". Please advise.

Replies are listed 'Best First'.
Re: Eliminating last comma
by japhy (Canon) on Jun 21, 2006 at 13:13 UTC
    To remove a trailing comma from a string, all you need is $string =~ s/,$//;

    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: Eliminating last comma
by Fletch (Bishop) on Jun 21, 2006 at 13:34 UTC

    No one's mentioned it yet (that I noticed), but this could be an XY problem with the actual solution being use join( ",", @names ) instead of whatever method you're using now that's leaving a trailing comma (like appending "$x," inside a for loop, for example).

Re: Eliminating last comma
by dorward (Curate) on Jun 21, 2006 at 13:13 UTC

    You don't need to match the entire string, just the bit you want to modify.

    my $myNames = "Jones, Smith, Baker, Johnson,"; $myNames =~ s/,$//;
Re: Eliminating last comma
by davorg (Chancellor) on Jun 21, 2006 at 13:13 UTC

    There's no need for the $myNames variable in the regex or the substitution string.

    $my_text =~ s/,$//;

    But it might be easier to just not add the last comma in the first place.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Eliminating last comma
by sgifford (Prior) on Jun 21, 2006 at 16:03 UTC
    Another option: if the last character is always a comma, then you really just want to remove the last character, which you can easily do with chop($myNames).
Re: Eliminating last comma
by dsheroh (Monsignor) on Jun 21, 2006 at 15:23 UTC
    I know the "$" matches the last character but not sure how to eliminate the ",".

    If so, then you know wrong. $ matches the end of the string (just after the last character), not the last character itself. (It's also possible that you just phrased it unclearly, but I figure better safe than sorry...)

    Aside from that, avoid adding the comma in the first place if possible (probably by using join to buld the string), use s/,$// if not, just like others have said.

Re: Eliminating last comma
by Joost (Canon) on Jun 21, 2006 at 13:14 UTC
      You people on here are quick!

      Thanks!!
A reply falls below the community's threshold of quality. You may see it by logging in.