Re: passing regular expression
by moritz (Cardinal) on Oct 08, 2009 at 06:27 UTC
|
my $re = qr{^yikes}i;
your_sub($re, $other, $arguments);
Perl 6 - links to (nearly) everything that is Perl 6.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
thank you,
Is it possible to write a subroutine which can take regular expression like split function does.
@a = split(/ /,"this is a string");
| [reply] [Watch: Dir/Any] [d/l] |
|
I don't think that's possible for non-builtin functions. If it is, it might work with a prototype, see perlsub.
| [reply] [Watch: Dir/Any] |
Re: passing regular expression
by Bloodnok (Vicar) on Oct 08, 2009 at 09:22 UTC
|
| [reply] [Watch: Dir/Any] [d/l] [select] |
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. | [reply] [Watch: Dir/Any] |
|
my $digit = "\\d";
-vs-
my $digit = qr/\d/;
It can also be faster (since qr// compiles up front). | [reply] [Watch: Dir/Any] [d/l] |
|
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.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
|