简体   繁体   中英

Perl regex replace slashes for converting path between windows and linux

I came across this solution, but cannot find any documentation about the "#" operator, can someone explain or point me to some useful references for this? Thanks!

$path =~ s#\\#/#g;  # convert backslash to forward slash.

When you use a regular expression, the conventional approach is to use a / character as a delimiter, eg:

s/pattern/replacement/g;

But you can use any character instead of a / , for example a pipe:

s|pattern|replacement|g;

This is useful if you want to use a / in your pattern. Normally you would have to escape every slash with a backslash so that they don't get interpreted as delimiters. But if you use a different delimiter then you don't need the escaping. These are equivalent:

s/\\/\//g;
s#\\#/#g;

The mixture of forward slashes and backslashes in the top one is referred to as "leaning toothpick syndrome". It's also worth noting that if the delimiter you use is part of a pair then you would use the closing version to terminate the regex:

s{\\}{/}g;

You can also use different delimiters on a match (rather than a substitute as shown above) but you'll need to include the m match operator prefix:

if ( $request =~ m{please}i ) {
    $approved = 1;
}

It's also worth noting that Perl on Windows is perfectly happy to use pathnames with forward slashes eg:

open my $fh, '<', 'C:/Temp/file.txt';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM