Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

add single backslash

by rhymejerky (Beadle)
on Apr 05, 2010 at 19:05 UTC ( [id://832884]=perlquestion: print w/replies, xml ) Need Help??

rhymejerky has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have two strings that look like '8\\.' and '8__BACKSLASH__.'. I would like to convert both to '8\.', how can I do that? I have tried to use regexp, but it just keeps on adding '\' to it. Thanks, R

Replies are listed 'Best First'.
Re: add single backslash
by kennethk (Abbot) on Apr 05, 2010 at 19:19 UTC
    What regular expressions did you try? Please post code, since you'll usually get better guidance in improving your programming skills that way.

    Since there are backslashes involved more care is required to get good results. However, this can be implemented with something like:

    #!/usr/bin/perl use warnings; use strict; my $regex_1 = '\\\\'; # Need pairs because of escaping my $regex_2 = '__BACKSLASH__'; for (<DATA>) { s/\Q$regex_1\E|\Q$regex_2\E/\\/g; print; } __DATA__ 8\\. 8__BACKSLASH__.

    Of particular note, I've used \Q and \E to escape regular expression metacharacters - omitting this is my guess on why you were having issues. See Quote and Quote like Operators in perlop for info on these.

      I was actually doing the exact same thing. The issue was I was reading the data through perl -d and was using the 'x' command. Should have used the 'p' command to print the data instead. That's why I was seeing that extra '\'. Thanks for your help though
Re: add single backslash
by ikegami (Patriarch) on Apr 05, 2010 at 20:23 UTC
    \ is special in string literals (pieces of code that build strings, incl the replacement expression of s///) and in regex patterns. Escaping it with another \ will cause it to be treated literally.
    for ( '8\\\\.', # 8\\. '8__BACKSLASH__.', ) { my $s = $_; $s =~ s/\\\\|__BACKSLASH__/\\/g; print "$s\n"; }
    8\. 8\.
Re: add single backslash
by CountZero (Bishop) on Apr 05, 2010 at 19:54 UTC
    $string = '8\.' if $string eq '8\\.' or $string eq '8__BACKSLASH__.',

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (3)
As of 2024-03-29 15:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found