Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Common Perl Pitfalls

by JavaFan (Canon)
on Apr 10, 2012 at 06:49 UTC ( #964264=note: print w/ replies, xml ) Need Help??


in reply to Common Perl Pitfalls

Of course if you had meant the string $to_replace is an actual regex to match against, you're better off using the qr operator:
I don't get this point. You started off that section with:
$to_replace='some_string'; $my_string=~ s/$to_replace/$better_data/;
and doomed this catastrophically unsafe, because $to_replace may actually contain characters that have a special meaning.

But if $to_replace is actually a regexp, the premises is gone -- any special characters are intentional. In fact, it's quite fine in that case to use the above.


Comment on Re: Common Perl Pitfalls
Download Code
Re^2: Common Perl Pitfalls
by Joe_ (Beadle) on Apr 10, 2012 at 18:21 UTC

    I actually meant to say that one shouldn't use a scalar as a regex anyway. I meant to say that, even if your correct semantics didn't require the use of \Q and \E (i.e. you actually needed the metacharacters) then you're better off using the qr// operator instead of building your regex as a literal string.

      Well, that's nice you want to say that, but can you back up your statement with an argument?

        Several, actually.
        For starters, I happen to believe it's better for readability. Another thing is, the regex modifiers "come with it". So you can include things like the 'x' modifier right along with the regex; if you're using a string as a regex, on the other hand, you have to remember which modifiers you need when you finally decide to use it in a match.
        Also, even though it doesn't show in this example, qr// is more efficient as (IIRC) it pre-compiles its regex before matching: i.e. you can build the regex once and use it several times. I use the qr// operator this way to make my regexes "modular".
        Anyway, you already know that I've been wrong about efficiency before :), so please correct me if you have a different say on the matter. I'm here to learn...

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2015-07-02 04:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (27 votes), past polls