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
2010-03-20 18:49:47
I'd write `$test =~ s[/$][]` for readability.
David Dorward
2010-03-21 15:36:33
Use the \z anchor to get the absolute end of string.
brian d foy
2010-03-22 15:41:21
+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
2010-03-20 18:50:11
Useless use of capturing group, and if the string contains new lines it will break too.
Qtax
2010-03-21 15:36:21
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
2010-03-22 15:27:45
+4
A:
$test =~ s/\/\z//;
You can use some other delimiter instead of /
, to avoid backslashing:
$test =~ s!/\z!!;
eugene y
2010-03-20 19:07:45
+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
2010-03-20 19:09:51