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

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 :)

Replies are listed 'Best First'.
Re^3: Use global flag when declaring regular expressions with qr?
by choroba (Cardinal) on Oct 28, 2024 at 18:23 UTC
    > 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]
Re^3: Use global flag when declaring regular expressions with qr?
by unmatched (Sexton) on Oct 28, 2024 at 15:20 UTC
    Awesome, thanks very much. I'll be sure to read up on that!