views:

190

answers:

3

I want to substitute, the "\" that appears in the Windows directory link to a "/". I tried using s//\////g, but it doesn't seem to do the trick.

+11  A: 
s[\\][//]g
  • \ needs to be escaped in a regex
  • / does not
  • Avoid using / to delimit regex sections when using / in the expression itself (it makes things much more readable!)

... but you should probably use something like Path::Class.

David Dorward
s[\\][//]g on "C:\Documents and Settings\fixxxer\Desktop\abc" is giving me = C:Documents and SettingsfixxxerDesktopabc.Help!!
fixxxer
\ is the escape character in a double quoted string. So `"C:\Documents"` is trying to interpret `\D` as a special thing like `\n` for newline. But there is no `\D` so its just coming out as `D`. If you turn on warnings Perl will tell you "Unrecognized escape". Use single quotes which does not escape (almost) anything. Also make sure your input is what you think it is with a simple print statement. PS I'd recommend Path::Class instead, far more complete and reliable.
Schwern
Using `s{\\}{//}g` with braces is probably a *little* more standard, but not by too much. You can use all sorts of garbage as delimiters to the `s` operator. :)
fennec
+1 for Path::Class.
Makis
+5  A: 

First of all, using a different separator than \ will make your regex more readable.

Then you have to replace the \ with \\, or it will be used to escape the following character (a / in the regex you are using).

$link =~ s|\\|//|g;
philippe
I think this is more readable than [][]
+2  A: 

I think this should do it:`

$str =~ s{\\}{//}g; 
fixxxer