in reply to Style question: regex versus string builtin function

Use index. Even after using \Q, there are other odd cases lurking. From perlreref
If 'pattern' is an empty string, the last I matched regex is used.
Also
You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be matched. You'll need to write something like m/\Quser\E\@\Qhost/.
The real 'style' question here, though, is Which form is most maintainable, most understandable when somebody looks at it two years from now? And this use of the $DELIMITER is going to be rather opaque in either case. Therefore, the most important element of style here is a generous set of comments, explaining why $DELIMITER was broken out a separate variable (or constant.)

throop

Update: lidden's point is well taken; even a zero-width assertion like \Q keeps the pattern from being empty. But see the discussion that follows

  • Comment on Re: Style question: regex versus string builtin function

Replies are listed 'Best First'.
Re^2: Style question: regex versus string builtin function
by lidden (Curate) on Oct 02, 2007 at 12:03 UTC
    But 'pattern' is not an empty string after using \Q.
      Silly enough this still counts as empty. In general I think the way empty regexes work is just bad design. It should only trigger if the regex is empty at the literal code level, not after all kinds of expansion has been done on the stuff between the delimiters.

      A \Q does not "fill" an empty regex.

      use Test::More 'tests' => 5; ok( 'foo' =~ //, 'empty regex matches' ); ok( 'foo' =~ /foo/, '/foo/ matches' ); ok( !('bar' =~ //), 'repeated match of foo' ); ok( !('bar' =~ /\Q/), 'repeated match with \\Q' ); my $empty = ''; ok( !('bar' =~ /\Q$empty/), 'interpolated empty string same as \\Q' );
        Well, dang!

        I'd recommended using index because of (inter alia) some gnarly behavior with empty patterns. But it turns out it was even more gnarly than I thought.

        BTW, perlreref says

        If 'pattern' is an empty string, the last I matched regex is used.
        What is the 'I' in 'I matched'? I couldn't find it mentioned again in perlre or perlreref, and searching on 'I' turned out to be ... overproductive.

        throop

Re^2: Style question: regex versus string builtin function (\Q not an assertion)
by lodin (Hermit) on Oct 14, 2007 at 22:55 UTC

    a zero-width assertion like \Q

    \Q isn't an assertion. It's like \U et al. and works in all interpolating quote operators. It's just that one almost always sees it with the regexp operators. An example:

    print "\U\Qfoo.bar"; __END__ FOO\.BAR

    lodin