Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: add a character at the end of a string

by reasonablekeith (Deacon)
on Dec 13, 2005 at 11:27 UTC ( [id://516286]=note: print w/replies, xml ) Need Help??


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

I always do it like this...
$string =~ s|/?$|/|;

although there are countless other ways. This one works by matching a trailing slash (if there is one) and 'replacing' it with a new trailing slash.

an alternative would be as follows..

$string .= '/' if $string !~ m|/$|;
---
my name's not Keith, and I'm not reasonable.

Replies are listed 'Best First'.
Re^2: add a character at the end of a string
by rsennat (Beadle) on Dec 13, 2005 at 11:37 UTC
    If I am right, /?$ means, the last slash in the string is replaced with /.

    can you get me any links or nodes here to read more on perl substitution operator.

    Thanks
    rsennat
      ok, here goes...

      the / means just that, match a forward slash
      the ? then says that you don't have to match the preceding character, but it will try to if it's there
      Finally the $ ties the match to the very end of the string

      So, if your string ends with a / it will be matched, and replaced with another slash, with no net effect.

      However, if your script doesn't end with a slash, the whole substitution still matches because the slash was optional. In this case all we're matching is the 'end' of the string. The substitution then replaces this (zero-width) match with the new slash, which has the net effect in inserting the trailing slash.

      for futher reading I’d recommend ‘perldoc perlre’ and the excellent “Mastering Regular Expressions” published by O’Reilly (which is superb)

      ---
      my name's not Keith, and I'm not reasonable.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-03-28 18:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found