in reply to Composing regex's dynamically

An alternative would be to construct the final regex from the parts:

my @parts = qr/this-stuff/; if ($foo_needed) { push @parts, qr/more-stuff/i; }; my $r = join "|", @parts; $r = qr/$r/; # just to be explicit about what the string is supposed t +o contain

Replies are listed 'Best First'.
Re^2: Composing regex's dynamically
by John M. Dlugosz (Monsignor) on Apr 27, 2011 at 13:48 UTC
    You are joining strings, yet @parts contains compiled re's. Wouldn't that join the stringified forms of the regex's, not the compile stuff itself?

    But I see the general point: Given $r1 and maybe $r2 as compiled regexs, I could say $r= qr/$r1|$r2/ Or if absent say $r=$r1;.

    I'm finding that I'm limited in how I break up a huge regex into separate pieces. Pieces can contain named captures and MARK:names, and the assembled result works the same as if it were written as one big string. But a named recursive reference (?&name) must be present when the regex is compiled, not (just) when it is used later.

      Regexes and strings are interchangeable. "Joining" two regexes (by interpolating them into a third) will join their stringified versions.

      If you want to "compile" a string to a regex, use qr() on the final string, like I did.

        One nice thing about Perl that's not present in other languages is that Regex is handled intrinsically rather than having to be a plain string first. That means, in particular, that we don't have to double-escape everything. \{ in a string literal becomes plain {, so you would have to write \\{ to get what you would normally write as \{ in a regular expression literal.

        So, you are saying that I can write the pieces as qr's (not plain strings), and the stringized form has everything escaped out so if I compile it again I get back the same regex?

        If I can mix qr literals and strings more freely without worrying, it will indeed be simpler.