Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: add a character at the end of a string

by Tomte (Priest)
on Dec 13, 2005 at 11:40 UTC ( [id://516290]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://516290]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-25 19:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found