开发者

How can I unescape backslashes in a Perl string?

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 nee开发者_Go百科ded
#$file_path ="\\abc.com\a\t\temp\L\";
printf $file_path;


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\


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

s/^\\\\|\\\\$/\\/g


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜