in reply to passing regular expression

Note that you don't have to use qr to pass regular expressions. You can also pass strings - Perl will compile a string into a regexp if used as a regexp.

Specially if the subroutine doesn't always actually use the regexp, you may avoid some regexp compilation this way.

Replies are listed 'Best First'.
Re^2: passing regular expression
by ikegami (Patriarch) on Oct 08, 2009 at 14:06 UTC

    Correct. It's just very convenient.

    my $digit = "\\d"; -vs- my $digit = qr/\d/;

    It can also be faster (since qr// compiles up front).

      It can also be faster (since qr// compiles up front)
      But it still compiles onces. my $digit = '\d'; /$digit/; only compiles a regexp once as well. And so does my $digit = '\d'; /$digit/ for 1 .. 100000.

      Note that my $digit = qr /\d/; /$digit/ if rand(2) < 1 always compiles a regexp once, m $digit = '\d'; /$digit/ if rand(2) < 1 compiles a regexp only 50% of the time.

      Whether or not passing a pattern as a compile regexp or as string is faster depend on what the subroutine is doing with it. Compiling the pattern up front means you're going to pay the price, regardless whether you need it. Passing it as a string means you're only going to pay the price if pattern is actually needed as a regexp.

        my $digit = '\d'; /$digit/; only compiles a regexp once as well.

        Perhaps, but that's not the OP's usage.

        my $digit = qr/\d/; foo($digit); # Compiles once my $digit = '\\d'; foo($digit); # Compiles any number of times

        Whether or not passing a pattern as a compile regexp or as string is faster depend on what the subroutine is doing with it.

        I said that in the post to which you are replying.

        Totally OT, but if you hadn't noticed - your post is no. 800000

        Just a something something...