tags:

views:

504

answers:

4

I would like to remove a trailing slash from a string. For example if i have a string called $test = "test/". How would I remove the slash at the end?

+10  A: 

With a regular expression do: $test =~ s/\/$//

Alternatively, if you're sure the last character is going to be a slash, you can use the chop function: chop $test

miorel
I'd write `$test =~ s[/$][]` for readability.
David Dorward
Use the \z anchor to get the absolute end of string.
brian d foy
+1  A: 

If you are sure that there is one / at the end all the time you can use the chop function:

$test = "test/";
$test = chop($test);

If you are not sure you can do:

$test = "test/";
$test = $1 if($test=~/(.*)\/$/);
codaddict
congrats on 10k reputation
Zerobu
@Zerobu: Thanks buddy :)
codaddict
Useless use of capturing group, and if the string contains new lines it will break too.
Qtax
Wow, both of these examples are wrong. You have to test to see that the last character is a / if you use chop, and the $ anchor allows a newline after the last character. Instead of a match, just use a substitution: `s|/\z||;`
brian d foy
+4  A: 
$test =~ s/\/\z//;

You can use some other delimiter instead of /, to avoid backslashing:

$test =~ s!/\z!!;
eugene y
Great minds think alike ....
justintime
Use the \z anchor to get the absolute end of string.
brian d foy
thanks, @brian.
eugene y
+5  A: 

Personally I would rephrase this to avoid the mixture of "\" and "/"

$test =~ s|/$||

If you use "|" you don't need to quote the "/"

justintime
Use the \z anchor to get the absolute end of string.
brian d foy