http://www.perlmonks.org?node_id=799867

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

can you tell me how to pass a regular expression to a subroutine?

Replies are listed 'Best First'.
Re: passing regular expression
by moritz (Cardinal) on Oct 08, 2009 at 06:27 UTC
    Just like any other argument, really.

    For creating the regex object it helps to use the qr{...} quoting construct:

    my $re = qr{^yikes}i; your_sub($re, $other, $arguments);
    Perl 6 - links to (nearly) everything that is Perl 6.
      thank you, Is it possible to write a subroutine which can take regular expression like split function does.
      @a = split(/ /,"this is a string");
        I don't think that's possible for non-builtin functions. If it is, it might work with a prototype, see perlsub.
Re: passing regular expression
by Bloodnok (Vicar) on Oct 08, 2009 at 09:22 UTC
    As moritz suggests, use pre-compiled REs - have a look at Test::More, in particular the subs: like() & unlike(), for examples.

    A user level that continues to overstate my experience :-))
Re: passing regular expression
by JavaFan (Canon) on Oct 08, 2009 at 11:57 UTC
    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.

      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.