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

I am trying to get rid of the string at the end of my query. $query =~ s/,$//; Cannot seem to get the syntax right. Appreciate any help! Thanks, Brian

Replies are listed 'Best First'.
Re: replace comma at the end of my query
by hardburn (Abbot) on May 09, 2003 at 18:11 UTC

    Hrm, just guessing, but are you building your query like the following:

    # @TERMS defined elsewhere my $query = 'SELECT '; foreach my $term (@TERMS) { $query .= "$term,"; } $query .= 'WHERE foo = ?';

    If so, try this instead:

    my $query = 'SELECT ' . join(',', @TERMS) . 'WHERE foo = ?';

    As for your orginal question, try using '\z' instead of '$'. '$' is supposed to match the end of a line. In other words, a new line. '\z' is usually more correct. The two are often interchangable, but will bite you when you confuse the two.

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      word up! worked beautifully! yep ... i was building my query statement based on whether or not values were present, if the value was present, then i added onto the query so i had that last comma at the end that wasnt need. thanks!
Re: replace comma at the end of my query
by Abstraction (Friar) on May 09, 2003 at 18:09 UTC
    Why use a regex when chop will do? Assuming, of course, you know the last character in your string will always be a comma.

    Otherwise this will work:
    $query =~ s/,$//;
      s/chop/substr/
      substr($query, -1,1)='' if substr($query, -1,1) eq ',';
      *note, I use substr($query, -1,1)='' instead of substr($query, -1,1,'') cause you never know how old the perl is ;)


      MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
      I run a Win32 PPM repository for perl 5.6x+5.8x. I take requests.
      ** The Third rule of perl club is a statement of fact: pod is sexy.