0

I have a Perl function as shown below, and it is taking a longer time to execute. (Note: This function is being called more than 10,000 times.)

After googling some, I found that If I can precompile a Perl regex then the execution time may decrease.

How can I modify a Perl regex so that it takes less time? Or is there a better solution?

sub some_func {
    my $var1=shift;
    my $var2=shift;

    if (!($var1 =~ /^UTF-?8$/)) {
         print "Do something important\n";
    }
    if ($var2 =~ /$some_global_string/i) {
         print "Do something important\n";
    }
}

E.g., $var2 can be

"character string with maximum 4096 character, Including html character as string"

and $some_global_string can be:

"string as $var2 but max length of 256 character"`
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Chirag
  • 607
  • 1
  • 6
  • 17
  • Please given an example of the content of `$var2` and `$some_global_string` – Håkon Hægland Oct 23 '18 at 13:21
  • @HåkonHægland Thanksfor the reply, I have edited the same details in question, Please have a look – Chirag Oct 23 '18 at 13:27
  • 2
    Possible duplicate of [Is there a way to precompile a regex in Perl?](https://stackoverflow.com/questions/952998/is-there-a-way-to-precompile-a-regex-in-perl) – blhsing Oct 23 '18 at 13:35
  • The most general answer (also covers substitutions like `s/(\w+)/\u\L$1/g;` (in variables/external data), not just simple fixed strings in variables) is [bart's answer to *Passing a regex substitution as a variable in Perl*](https://stackoverflow.com/questions/125171/passing-a-regex-substitution-as-a-variable-in-perl/128321#128321) – Peter Mortensen Apr 28 '21 at 18:25

1 Answers1

4

http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators

my $RE1 = qr/^UTF-?8$/;
my $RE2 = qr/$some_global_string/i;
....
if ($var1 !~ /$RE1/) {...};
...
if ($var2 =~ /$RE2/) {...};
UjinT34
  • 4,784
  • 1
  • 12
  • 26
  • Thanks, Can you please confirm, Is this $var1 !~ or $var1 =~ ?? – Chirag Oct 23 '18 at 13:42
  • 1
    That depends entirely on your use case @Chirag. It doesn't matter if you do a positive or negative match. The relevant info is that the `qr//` operator creates a pre-compiled pattern, and you'd do that in a larger scope or with `state`. – simbabque Oct 23 '18 at 13:45
  • Ok, Thanks, I just wanted to check if it was intentional or typo :) – Chirag Oct 23 '18 at 13:46