Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

replace / with \ using regular expressions?

by Anonymous Monk
on Jun 20, 2009 at 07:31 UTC ( [id://773195]=perlquestion: print w/replies, xml ) Need Help??

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

How to replace the '/'with '\' using regular expression?
  • Comment on replace / with \ using regular expressions?

Replies are listed 'Best First'.
Re: replace / with \ using regular expressions?
by davorg (Chancellor) on Jun 20, 2009 at 13:33 UTC

    For replacing a single, known character, then regular expressions are the wrong tool. You need the tr/// operator as has already been pointed out.

    The difference in performance is impressive:

    $ cat bench #!/usr/bin/perl use strict; use warnings; use Benchmark 'cmpthese'; sub regex_subst { $_ = 'this/is/a/string'; s|/|\\|g; } sub tr_subst { $_ = 'this/is/a/string'; tr|/|\\|; } cmpthese(1_000_000, { s => \&regex_subst, tr => \&tr_subst, }); $ ./bench Rate s tr s 287356/s -- -75% tr 1162791/s 305% -- $
    --

    See the Copyright notice on my home node.

    Perl training courses

      You need the tr/// operator

      No, you don't need it. TIMTOWTDI, and s///g is as understandable and easy to write just like tr///.

      The difference in performance is impressive

      But typically completely irrelevant for the performance of scripts/programs of any size. This optimization feels pretty immature.

      When will doing 287356 of these operations per second ever be anything other than fast enough?

      hi daveorg, Thanks for making this clear to me.
        I would just point out that the Perl functions on Windows don't care about / vs \. If you calling a Perl function leave it in a/b/xyz format. Of course a command to the Windows shell is different.
Re: replace / with \ using regular expressions?
by Anonymous Monk on Jun 20, 2009 at 07:42 UTC
    $command =~ s!/!\\!g;    # Swap '/' for '\'

      tr|/|\\| should be more efficient.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        thanks Alex.
      I have string say C:/this/is/atest/ i need to replace this with C:\this\is\atest\?
        What the problem is?
        $command = 'C:/this/is/atest/'; $command =~ s!/!\\!g; # Swap '/' for '\' die $command; __END__ C:\this\is\atest\ at - line 3.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2024-04-24 20:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found