Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Escape special chars in a path

by johngg (Canon)
on Aug 17, 2022 at 21:26 UTC ( #11146205=note: print w/replies, xml ) Need Help??


in reply to Escape special chars in a path

This is more of an observation rather than answering your question but using alternative delimiters in your substitutions can make the code much easier to read. Also I find that it is easier to use the hex value for a backslash rather than the character itself, e.g. converting to Unix-style paths ...

johngg@aleatico:~$ perl -Mstrict -Mwarnings -E 'say q{}; my( $path ) = qw{ C:\Users\fred\file.txt }; say $path; $path =~ s{\x5c}{/}g; say $path;' C:\Users\fred\file.txt C:/Users/fred/file.txt

Going the other way, I would use a lookahead, the chr function and the e modifier in a substitution to do escaping.

johngg@aleatico:~$ perl -Mstrict -Mwarnings -E 'say q{}; my( $path ) = qw{ C:\Users\fred\file.txt }; say $path; $path =~ s{(?=\x5c)}{ chr 92 }eg; say $path;' C:\Users\fred\file.txt C:\\Users\\fred\\file.txt

It seems easier to my eyes. I hope this is helpful.

Cheers,

JohnGG

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11146205]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2023-02-01 12:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (0 votes). Check out past polls.

    Notices?