Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: replace / with \ using regular expressions?

by davorg (Chancellor)
on Jun 20, 2009 at 13:33 UTC ( [id://773239]=note: print w/replies, xml ) Need Help??


in reply to replace / with \ using regular expressions?

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

Replies are listed 'Best First'.
Re^2: replace / with \ using regular expressions?
by Juerd (Abbot) on Jun 21, 2009 at 23:09 UTC

    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?

Re^2: replace / with \ using regular expressions?
by Anonymous Monk on Jun 20, 2009 at 14:22 UTC
    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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (6)
As of 2024-04-23 16:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found