However, there are other problems with what you're doing.
You're repeating that interpolation on every trip through the loop, when you could be using qr// to compile your regex once and then forget about it.
Here are some comparisons of a few of the other solutions mentioned in this thread, along with one where the regex is pre-built with qr//. These results are with 5.6.1 on cygwin; YMMV.
The benchmark code is here:$ perl testLocal.pl Benchmark: running localWhile, localWhileQR, whileLocal, each for at l +east 3 CPU seconds... localWhile: 4 wallclock secs ( 3.02 usr + 0.00 sys = 0.02 CPU) @ 28 +894.20/s (n=87116) localWhileQR: 4 wallclock secs ( 3.17 usr + 0.01 sys = 3.18 CPU) @ +45765.70/s (n=145718) whileLocal: 4 wallclock secs ( 3.09 usr + 0.00 sys = 3.09 CPU) @ 20 +884.62/s (n=64617) Rate whileLocal localWhile localWhileQR whileLocal 20885/s -- -28% -54% localWhile 28894/s 38% -- -37% localWhileQR 45766/s 119% 58% --
$ cat testLocal.pl #!/usr/bin/perl -w use strict; use Benchmark qw(cmpthese); my @a=qw(a x z); # if you increase the number of test strings, the differences # get even more pronounced... my @strings=qw(a x z vvvvv vvvvva vvvvvb vvvvvx vvvvvz aaa axz azz axx +); sub localWhile{ local $"=""; my $count; foreach(@strings) { $count++ if /^[@a]{3}$/; } die unless $count==4; } sub whileLocal{ my $count; foreach(@strings) { local $"=""; $count++ if /^[@a]{3}$/; } die unless $count==4; } sub localWhileQR{ my $count; local $"=""; my $re=qr/^[@a]{3}$/; foreach(@strings) { $count++ if /$re/; } die unless $count==4; } cmpthese(-3, { localWhile => \&localWhile, localWhileQR => \&localWhileQR, whileLocal => \&whileLocal } );
In reply to Re: Character class in an array
by RMGir
in thread Character class in an array
by nikto
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |