manishrathi has asked for the wisdom of the Perl Monks concerning the following question:

I have a string as
$test = "C:\first\second";
I want output as "C:/first/second"
I have used following code
$test = "C:\first\second";<br><br> print $test;<br> print"\n\n";<br> $test =~ s/\\/\//g;<br> print $test;
I am saving this code as invertSlash.pl. When I execute this code, I am getting following output

C:\Users\Admin\Desktop\perl_programs>perl invertSlash.pl<br> C:Širstsecond<br><br> C:Širstsecond


Whats wrong with this code, why am I not getting proper output as required ?

Thanks

Replies are listed 'Best First'.
Re: replacing backward slash with forward slash
by davido (Cardinal) on Aug 19, 2011 at 08:33 UTC
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: replacing backward slash with forward slash
by Anonymous Monk on Aug 19, 2011 at 08:23 UTC

    Whats wrong with this code, why am I not getting proper output as required ?

    You're not providing proper input as requires (GIGO)

    Read perlintro and learn to single quote

Re: replacing backward slash with forward slash
by pvaldes (Chaplain) on Aug 19, 2011 at 13:54 UTC
    Some people could want to use something like this instead, same result, different notation
    $test = 'C:\first\second'; print $test, "\n"; $test =~ tr,\\,\/,; #or $test =~ tr [\\] [\/]; #or $test =~ tr <\\> <\/>; #or even $test =~ tr .\\.\/.; print $test, "\n";
    I personally find it easier to read

      Actually you don't need the backslash escape for the slash if you use a different character for the delimiter.

      use strict; use warnings; my $test = 'C:\first\second'; print $test, "\n"; $test =~ tr,\\,/,; #$test =~ tr [\\] [/]; #$test =~ tr <\\> </>; #$test =~ tr .\\./.; print $test, "\n";

      'tr' is also slightly more efficent than 's' since it doesn't have to try to evaluate as a regrex. (Of course, it's less powerful as well.)