11

Similar to this, how do I achieve the same in Perl?

I want to convert:

C:\Dir1\SubDir1\` to `C:/Dir1/SubDir1/

I am trying to follow examples given here, but when I say something like:

my $replacedString= ~s/$dir/"/"; # $dir is C:\Dir1\SubDir1\

I get a compilation error. I've tried escaping the /, but I then get other compiler errors.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
user375868
  • 1,288
  • 4
  • 21
  • 45

4 Answers4

29

= ~ is very different from =~. The first is assignment and bitwise negation, the second is the binding operator used with regexes.

What you want is this:

$string_to_change =~ s/pattern_to_look_for/string_to_replace_with/g;

Note the use of the global /g option to make changes throughout your string. In your case, looks like you need:

$dir =~ s/\\/\//g;

If you want a more readable regex, you can exchange the delimiter: s#\\#/#g;

If you want to preserve your original string, you can copy it before doing the replacement. You can also use transliteration: tr#\\#/# -- in which case you need no global option.

In short:

$dir =~ tr#\\#/#;

Documentation:

TLP
  • 66,756
  • 10
  • 92
  • 149
6

You're splitting the =~ operator and missing the global modifier. Just assign $dir to $replacedString and then do the substitution.

my $replacedString = $dir;
$replacedString =~ s|\\|/|g;

You can use tr, the translate operator, instead of the s operator too to get simpler code.

my $replacedString = $dir;
$replacedString =~ tr|\\|/|;
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
6

You might actually be looking for File::Spec->canonpath or Path::Class without realizing it.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
-1
use warnings;    
use strict;    
my $str = 'c:/windows/';    
$str =~ tr{/}{\\};    
print $str;

Output:

c:\windows\

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Akshit
  • 69
  • 4
  • 13