Perl replacement
If you want a cross-platform way, use File :: Spec .
($volume,$directories,$file) = File::Spec->splitpath( $path ); @dirs = File::Spec->splitdir( $directories );
Then use catpath
to join him.
a source to share
Your attempt was almost right. Let's take a closer look:
$path = s/\\////
^
First, for substitution to work on a variable $path
, you need to use the bind operator=~
, not just the simple assignment operator. Then, since you used a regular forward slash character as your replacement separator, the forward slash above actually denotes the end of the substitution command, and the remaining two slashes are just garbage. It sounds like you might be thinking that the rule of thumb to bypass special properties of a character is to double it. If your only example is a backslash then this rule might make sense, but the rule is actually a prefix of special characters with backslashes... Replace the highlighted forward slash with a backslash and it becomes an escape character, so we bypass the special next forward slash function to treat it as a simple forward slash, allowing the replacement to complete correctly after that slash:
$path =~ s/\\/\//
But it's hard to read. Fortunately, you don't need to use the forward slash as the replacement separator; you can use almost any character you want. Choose a delimiter that is not like the text you are trying to replace and your code may be more readable. Details are in perlop under Quote and Quote- Like Operators . When a symbol of your choice forms a pair with another symbol, you use both to include the two parts of the expression. Also, since you probably want to replace all the slashes in your string, you should use a modifier g
at the end, telling it to match globally, rather than stop after the first substitution. Combine it all:
$path =~ s{\\}{/}g
Since you are replacing one character for another single character, you can use the more specialized transliteration operator instead . It is automatically applied all over the world. tr
s
$path =~ tr{\\}{/}
Finally, if this is more than just a one-off path (i.e. you do this multiple times in a script, or the script will be maintained for a while), or you need your code to do the same thing on multiple platforms, consider using File :: Spec . It allows you to split and combine path components using the right delimiter for whatever platform you are running on.
a source to share