tags:

views:

213

answers:

3

I need the to convert the input address to specified format

#!/usr/bin/perl
my $file_path ="\\\abc.com\a\t\temp\L\\";

#---- Help in this regex
$file_path =~ s//\//\/gi;

#---- Output format needed
#$file_path ="\\abc.com\a\t\temp\L\";
printf $file_path;
+2  A: 

If your \ in my $file_path are not the escape characters,

s/^\\\\|\\\\$/\\/g
KennyTM
the input address has two slashes at the end which sholud be made to one
kk
That's why there's a `/g` flag.
KennyTM
ok. how to print the address str without making perl take the slashes as escape characters. i dont want to alter the string by adding more escape characters also.
kk
Backslashes are *always* an escape character. You need write `$file_path='\\\\\\abc.com\\a\\t\\temp\\L\\\\';`.
KennyTM
+2  A: 

What you seem want to do is collapse every occurrence of \\ to \. However, you need to escape every occurrence of \ when you actually use it in your regexp, like so:

use strict; use warnings;

my $a = '\\\abc.com\a\t\temp\L\\';

# match \\\\ and replace with \\
(my $b = $a) =~ s/\\\\/\\/g;
print $b . "\n";

...which yields the literal string:

\abc.com\a\t\temp\L\

Note that I did not specify the input string with double quotes as you did. It is not entirely clear what the literal string is that you are starting with, as if it is specified with double quotes, it needs to have more backslashes (every two backslashes becomes one). See the discussion of interpolation under perldoc perlop, as I mentioned in an answer to your other question.

Ether
+3  A: 

I am guessing you want to normalise a UNC path, in which case the double \ at the beginning is important to keep, and the answers from Ether and KennyTM produce wrong results. Pick either one of the methods below.

use File::Spec qw();
print File::Spec->canonpath('\\\abc.com\a\t\temp\L\\');

use URI::file qw();
print URI::file->new('\\\abc.com\a\t\temp\L\\', 'win32')->dir('win32');

__END__
\\abc.com\a\t\temp\L\
daxim
+1 for File::Spec.
Paul Nathan