How to replace backslash in Perl?

Like this , how do I achieve the same in Perl?

I want to convert

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

I try to follow the examples below here , but when I say something like

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

I get a compilation error. I tried to avoid the slash, but then I get other compiler errors.

+7
source share
3 answers

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

What you want is:

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

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

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

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

If you want to keep the original string, you can copy it before performing a replacement. You can also use transliteration: tr#\\#/# - in this case you do not need a global option.

In short:

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

Documentation:

+21
source

You split the operator =~ and donโ€™t get the global modifier. Just assign $dir to $replacedString and then do the lookup.

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

You can use the tr translation operator instead of the s operator to get simpler code.

 my $replacedString = $dir; $replacedString =~ tr|\\|/|; 
+6
source

In fact, you can search for File :: Spec-> canonpath or Path :: Class without realizing it.

+6
source

All Articles