Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl next if regex stored in array

i have a piece of code with a a while loop and a couple of next if's like this in the loop :

LOOP:
while (something) {
   next if $UPUPRF =~ /^T[0-9]{6}/;
   next if $UPUPRF =~ /^SECURITE.*/;
   next if $UPUPRF =~ /^AUDIT[A-Z]{2}/;
}

i would like to put these regexes in my configuation file (a perl data structure) instead of having them "hardcoded" in the script, so that the user can edit them easily by just editing the configuration file, and would like your advice regarding this.

what is the cleanest way of doing this ?

first, i guess i can store the regexes like this in the configuration file ? (with qr//):

 ....
 exclude_acct => [
                    qr/^T[0-9]{6}/,
                    qr/^AUDIT[A-Z]{2}/,
                    qr/^SECURITE.*/,
                 ],
 ....

and in my loop, should i use something like this ? :

foreach (@{ $myhash{exclude_acct} }) {
    next LOOP if $UPUPRF =~ /$_/;
}

thanks for your advices.

regards

note : i haven't tried this code yet, just guessing that i could do it like that, but i'm mainly wondering if this is "clean" or if there is a cleaner way of doing it

like image 940
olivierg Avatar asked Nov 22 '25 20:11

olivierg


1 Answers

That's fine, but starting the regex engine is relatively expensive, so it would be faster than create one regex from the many.

# Once, before the loop.
my $pat = join "|", @{ $myhash{exclude_acct} };
my $re = qr/$pat/;

# In the loop.
next LOOP if $UPUPRF =~ $re;

This can break backreferences (\1), though.

like image 83
ikegami Avatar answered Nov 24 '25 10:11

ikegami



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!