How can I unescape backslashes in a Perl string?

后端 未结 3 1496
旧巷少年郎
旧巷少年郎 2021-01-29 00:09

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_         


        
相关标签:
3条回答
  • 2021-01-29 00:39

    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 讨论(0)
  • 2021-01-29 00:42

    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\
    
    0 讨论(0)
  • 2021-01-29 00:52

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

    s/^\\\\|\\\\$/\\/g
    
    0 讨论(0)
提交回复
热议问题