Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace backslash with forward slash in Perl?

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.

like image 948
user375868 Avatar asked Nov 04 '11 19:11

user375868


People also ask

What does backslash do in Perl?

The backslash operator can do more than produce a single reference. It will generate a whole list of references if applied to a list. As mentioned earlier, the backslash operator is usually used on a single referent to generate a single reference, but it doesn't have to be.


1 Answers

= ~ 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:

  • Perl operators
  • Regular expressions
like image 72
TLP Avatar answered Oct 19 '22 02:10

TLP