http://www.perlmonks.org?node_id=516290


in reply to add a character at the end of a string

I guess there are alternatives, but it works:

# can't be called with a literal string as arg # but that wasn't asked for :) sub appendMissingSlash { return $_[0] .= substr($_[0], -1) eq "/" ? "" : "/"; } my $string = "/tmp/check"; appendMissingSlash($string); print $string,"\n"; __END__ /tmp/check/

Update: I didn't use a regex, as other examples given suggest, because we know the position and the character to check for, using the regex engine seemed overkill to me

regards,
tomte


An intellectual is someone whose mind watches itself.
-- Albert Camus

Replies are listed 'Best First'.
Re^2: add a character at the end of a string
by jhourcle (Prior) on Dec 13, 2005 at 12:18 UTC
    I didn't use a regex, as other examples given suggest, because we know the position and the character to check for, using the regex engine seemed overkill to me

    I this case, it's a fixed length string, at the end of the string, so it's a rather efficient match with regex -- if you were really concerned with speed, you'd have not wanted to append an empty string when you didn't have to:

    In my opinion, it's a case of premature optimization, as with the differences so insignificant for the top three, it's not worth worrying about. (multiple runs don't have a consistent leader, and variations in versions of perl might cause different results) ... and odds are, this one replacement is a very small part of the overall program, so I wouldn't even be opposed to the slowest one, as it's the shortest to type.

      In my opinion, it's a case of premature optimization,
      In mine, it's a case of using the right tool for the job, not contradicted (again IMO) by the benchmark results :)

      regards,
      tomte


      An intellectual is someone whose mind watches itself.
      -- Albert Camus