user2461926
user2461926

Reputation: 23

Perl replacing \ in a string

I want to replace second occurrences of back slash in string, It could be very easy.

string

$ra = '\\Test\C$\temp';

output should be like this

"\\Test/C$/temp"

search and replace changes everything in the string

$ra =~ s/\\/\//g; makes output to "/Test/C$/temp"

any insight highly appreciated

Upvotes: 2

Views: 153

Answers (3)

ikegami
ikegami

Reputation: 385655

The string literal

 '\\Test\C$\temp';

creates the string

 \Test\C$\temp

So first, you need to use

 $ra = '\\\\Test\\C$\\temp';

Or if you want to cut corners,

 $ra = '\\\Test\C$\temp';

Then you can simply do

 $ra =~ s{(?<!^)(?<!^\\)\\}{/}g;

Note that Windows considers

 //Test/C$/temp

to be completely equivalent to

 \\Test\C$\temp

so I don't know why you're trying to accomplish what you said you wanted to accomplish.

Upvotes: 1

Julian Fondren
Julian Fondren

Reputation: 5619

"I want to replace ... back slash in string [with slashes]"

s,\\,/,g;

"First two occurrences of backslash remains"

s,(?<!^)(?<!^\\)\\,/,g;

Two zero-width negative lookbehind assertions are required as lookbehinds can't be of variable width. They succeed if the backlash isn't preceded by the start of a line or by the start of a line and then a backslash.

Upvotes: 2

perreal
perreal

Reputation: 97938

This may not be the best way, but you can use the e option:

$ra =~ s!^(.*?\\)(.*)!my ($e,$f)=($2,$1);$e=~s/\\/\//g;$f.$e!e;

or using split:

my @v = split /\\+/, $ra;
$ra = (shift @v) . '\\' . join("/", @v);

Upvotes: 3

Related Questions