How can I remove trailing commas?

Discussion in 'Perl Misc' started by Jame Pearl, Jan 30, 2006.

  1. Jame Pearl

    Jame Pearl Guest

    How can I remove any trailing commas from the end of $var?

    I tried using

    $var =~ s/,+$//

    but it didn't work.
    Jame Pearl, Jan 30, 2006
    1. Advertisements

  2. Jame Pearl

    Paul Lalli Guest

    "Didn't work" is the worst of all possible error descriptions. *How*
    did it not work? Did it not remove anything? Did it remove too much?
    Did you get a syntax error (and if so, what was it?) Did your program
    crash? Enter an infinite loop? *What happened*?

    Please read the Posting Guidelines for this group. Then post a
    short-but-complete example that we can run by copy and pasting, which
    demonstrates your supposed error.

    There is nothing wrong with that statement you have typed above.
    Therefore, you have misdiagnosed your problem or mis-retyped your
    actual code. This is why you are encouraged to create a
    short-but-complete program in preparation for posting here - doing so
    very often helps you find your *real* problem.

    Now, all that being said, I have to ask how this need arose in the
    first place? I've seen lots of bad code where people attempt to create
    a string composed of the elements of an array separated by a comma, and
    do so by concatenating each element of the array with a comma, and then
    remove the final comma, like so:

    my $string;
    foreach my $elem (@array) {
    $string .= "$elem,";
    $string =~ s/,$//;
    print "Values: $string\n";

    If you are doing that, please stop. Instead, look up:

    perldoc -f join
    perldoc perlop (search for the $, and $" variables)

    my $string = join(',', @array);
    print "Values: $string\n";
    # .... or....
    local $, = ',';
    print 'Values: ';
    print @array;
    print "\n";
    #..... or ...
    local $" = ',';
    print "Values: @array\n";

    Paul Lalli
    Paul Lalli, Jan 30, 2006
    1. Advertisements

  3. Works for me:

    use strict; use warnings;
    my $var = 'foo,,,,';
    print "$var\n";
    $var =~ s/,+$//;
    print "$var\n";

    Maybe your $var does not contain what you think it contains?

    Jürgen Exner, Jan 30, 2006
  4. Jame Pearl

    Dr.Ruud Guest

    Jame Pearl schreef:

    $var =~ s/,+$//m;

    does work, see `perldoc perlre` again.
    Dr.Ruud, Jan 30, 2006
  5. Perhaps $var contains trailing whitespace. Try:
    $var =~ s/,+\s+$//;
    Glenn Jackman, Jan 30, 2006
  6. This seals it for me. I have now been converted to the PBP recommendation
    precisely which I can never remember what m and s modifiers do:


    use strict;
    use warnings;

    my $var = "foo,\nbar,";
    $var =~ s{ ,\z }{ }msx;
    print "$var\n";


    C:\Home\asu1\Perl> perl
    A. Sinan Unur, Jan 30, 2006
  7. Jame Pearl

    Dr.Ruud Guest

    Abigail schreef:

    $var =~ s/,+$//gm;

    does even work better, then Jame's data is complexer than I was prepared
    to assume.

    Next episode:

    $var =~ s/,+(?=\s*$)//;

    (which also removes more than "trailing commas")

    And s/,+(?=\s*)$// isn't the same, see perlre:
    "two zero-width assertions next to each other work
    as though they're ANDed together"
    Dr.Ruud, Jan 30, 2006
  8. Jame Pearl

    DJ Stunks Guest

    The undead legions of Damian Conway's Perl Best Hacker Army welcome

    The rest of you be forewarned: resistance is futile; you will be

    PBH #12011
    DJ Stunks, Jan 30, 2006
  9. Jame Pearl

    Uri Guttman Guest

    DS> The undead legions of Damian Conway's Perl Best Hacker Army welcome
    DS> you.

    DS> The rest of you be forewarned: resistance is futile; you will be
    DS> assimilated.

    DS> PBH #12011
    DS> -jp

    i won't drink all of his koolaid! :) and i was a tech reviewer of
    PBP. just that some of his ideas are for some people and not for
    me. using \z is good and i will try to make that a habit but enabling /m
    and /s all the time just bothers me as i like don't like to do things
    with no technical purpose like that. i know what they mean just fine and
    use them when i need to.

    an important aspect of PBP is choosing which ideas will work for you and
    then being consistant about using them. that is something i support and

    Uri Guttman, Jan 30, 2006
  10. Jame Pearl

    ced Guest

    The OP didn't indicate whether $var might have a trailing newline
    after the comma or not but you could handle both cases:

    $var =~ s{ , (?: \z | \Z) }{ }msx;
    ced, Jan 30, 2006
  11. You don't have a COBOL compiler?

    John W. Krahn, Jan 30, 2006
  12. Jame Pearl

    ced Guest

    I was thinking of a newline just before a trailing comma:

    perl -e '$_ = "foo,\n,"; s{ , ( \z | \Z) }{}msx'' # result:

    The alternation (\z|\Z) strips the trailing comma in "foo,\n," and
    would strip
    the comma in just "foo,\n" as well.


    $ perl -e '$_ = "foo,\n,"; s{,$}{}msx' # result: "foo\n,"

    only picks up the leading comma.

    Yes, thanks. I mistakenly thought I saw a space in Sinan's
    replacement { }
    and figured he couldn't be wrong....:)
    ced, Jan 30, 2006
  13. But you were not mistaken. There indeed was a space in the replacement,
    and there should not have been.

    The reason I like posting here is because I am frequently wrong, and
    someone always corrects me in those cases.

    Now, if you had said you thought Abigail could not be wrong, then you
    would have a point.

    A. Sinan Unur, Jan 31, 2006
  14. Well it is.

    My response was to the following example you posted.

    ### $ perl -wle '$var = "foo,\nbar,"; $var =~ s/,$//m; print $var'
    ### foo
    ### bar,

    In this case, I am presuming that one would want to remove the comma
    after bar, and not the comma after foo.


    D:\> perl -wle "$var = qq{foo,\nbar,}; $var =~ s/,\z//m; print $var"

    or, as you pointed out, just leaving the m modifier would also do what
    is intended:

    D:\> perl -wle "$var = qq{foo,\nbar,}; $var =~ s/,$//; print $var"

    At this point, I realized that *I* always do have to look up the meaning
    of the 'm' and 's' modifiers. And, that is when Damian Conway's advice
    just seemed to make a lot of sense.
    Good point.

    A. Sinan Unur, Jan 31, 2006
  15. Jame Pearl

    ced Guest

    Point taken. Any rote maneuver -- whether adding \m as a matter of
    or auto-pasting from a previous post, eg, { } on the substitution RHS
    -- is
    usually either a mistake or adds confusing, unnecessary complexity.

    I still believe (\s|\S) -- without the unnecessary /ms -- is a
    useful idiom here
    to guarantee removal of the trailing character.
    ced, Feb 1, 2006
  16. Jame Pearl

    ced Guest

    I meant (\z|\Z) of course.
    ced, Feb 1, 2006
  17. Jame Pearl

    Anno Siegel Guest

    Here is how I keep them apart:

    /s stands for "single". It modifies the behavior of a single item,
    namely ".". /m stands for "multiple". It modifies the behavior of
    multiple (two) items, namely "^" and "$".

    Anno Siegel, Feb 1, 2006
  18. Jame Pearl

    Anno Siegel Guest

    Me, I chose to do everything according to PBP I have been doing that
    way all along. :)

    The need for a strict style guide varies -- it is much stronger in a
    team effort than in a one-man project. If I had to decide what language
    to use in a big project (I don't and I won't), one thing I would look
    for is a comprehensive style guide for the language to base my own on.
    Perl now has that. That may have a long-term effect on the eligibility
    of Perl for larger projects.

    Anno Siegel, Feb 1, 2006
  19. Jame Pearl

    ced Guest

    Your're right. \z just does half of what \Z does.
    No :) Somehow I conflated \Z with something that matched only
    a trailing newline. I've got it straight now..
    ced, Feb 2, 2006
  20. Jame Pearl

    ced Guest

    A bit far fetched perhaps but, if you had a burning need to know where
    the strip occurred:

    if ( s{ , (?: (\z) | (\Z) ) }{}x ) {
    print "stripped comma ", defined $1 ? "from end of string"
    : "before
    trailing newline";
    ced, Feb 2, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.