in reply to Use global flag when declaring regular expressions with qr?

Oh, I see. Thank you both, that seems to do the trick just fine :)

This makes me curious about something I read regarding the qr operator, and that is that it's supposed to compile the pattern provided as it's being saved into the variable. But, wouldn't this approach of enclosing it again with /$re/g, as in this case, defeat the purpose of it? Are there any penalties in terms of performance? Not that I actually care much about it right now, I'm just curious.

Thanks again!

PS: Do I need to mark this question as solved somewhere?

Replies are listed 'Best First'.
Re^2: Use global flag when declaring regular expressions with qr?
by ikegami (Patriarch) on Oct 28, 2024 at 15:15 UTC

    wouldn't this approach of enclosing it again with /$re/g, as in this case, defeat the purpose of it?

    No. $x =~ $y is already short for $x =~ m/$y/, so it doesn't add a penalty. And as per the last line of my answer, it's not stringified and recompiled when the entire pattern is a compiled regex, so the purpose isn't defeated.

    As for marking as "solved", you just did :)

      > it's not stringified and recompiled

      Interestingly, using a string is still faster than using a compiled regex (even when I wrap the string in (?:^...) like the compilation does).

      #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my $re = qr/^ *(?:say|print)/; my $s = qq/(?^:^ *(?:say|print))/; open my $in, '-|', qw{ perldoc perlfunc } or die $!; my @lines = <$in>; push @lines, @lines for 1 .. 5; say scalar @lines; use Benchmark qw{ cmpthese }; my ($ir, $is); cmpthese(-3, { regex => sub { $ir = 0; /$re/ and ++$ir for @lines }, string => sub { $is = 0; /$s/ and ++$is for @lines }, }); $ir == $is or die; __END__ 259616 Rate regex string regex 13.5/s -- -23% string 17.6/s 31% --

      Is it because of dereferencing of the regex object?

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Awesome, thanks very much. I'll be sure to read up on that!