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

Hi monks, I've got a really small, dummy question here.
I've red the tutorials but I still can work this out.
In basic terms, I have this string:
$query1 = "select foo,bar,baz,"
This has to be later concatenated with another string to form a SQL query.
My question is: how can I take the last comma away?
I want my finished string to look like this:
$query1 = "select foo,bar,baz"
Thanks for answering. Cheers :)

Replies are listed 'Best First'.
Re: How to take the last character out of a string
by duff (Parson) on Feb 16, 2005 at 20:03 UTC

    perldoc -f chop

    perldoc -f substr

    Alternatively you could build the string better to begin with. For instance:

    @stuff=qw(foo bar baz); $query = "select " . join (',', @stuff) . $rest_of_query;

    (just an example, caveat lector)

Re: How to take the last character out of a string
by Tanktalus (Canon) on Feb 16, 2005 at 20:05 UTC
    $query =~ s/,$//;

    Better, though, to not put it there:

    my @cols = qw(foo bar baz); $query1 = 'select ' . join (',',@cols);
    join is your friend :-)

Re: How to take the last character out of a string
by punch_card_don (Curate) on Feb 16, 2005 at 20:19 UTC
    Add commas in front of additional parameters, not after the last parameter.
    $query1 = "select foo"; $query1 = $query1.", bar";

    Forget that fear of gravity,
    Get a little savagery in your life.

Re: How to take the last character out of a string
by perlsen (Chaplain) on Feb 17, 2005 at 03:59 UTC

    Hi, just try this,

    $query1 = "select foo,bar,baz,"; $query1 =~ s#(.*),$#$1#gs; print "$query1"; #output #select foo,bar,baz

      No doubt, this works. But it's doing a lot of work it doesn't need to.

      • Copying the whole string around. You're matching the whole string, except for the terminating comma, and then copying it back into $query1.
      • And then you're going to search the string again, presumably in case there is a second ending comma.
      • And what is the 's' for? You may have a habit of using it, thinking it solves a lot of your problems. I think you might be cultivating a bad habit - perl probably does things as defaults that are good things, and you want to specify overriding behaviour only when you need it. (Minimalist theory.)

      For the first one, just get rid of the (.*) and $1: $query1 =~ s#,$##gs. For the second, just add an appropriate plus sign: $query =~ s#,+$##s. For the last, well, just remove the ending s - it's not doing anything: $query =~ s#,+$##.

      "Premature optimisation is the root of all evil." Well, I'm not optimising - I'm merely encouraging idiomatic use of perl: writing perl the way it should be. Minimally, but not unreadably. (The last part doesn't apply to obfu's and golf competitions.)