in reply to Feature Idea: qr//e (updated with solutions)

Instinctively I think a module exporting something like qre() (and more) would be better.

There are some edge cases to be monitored and warned, there are some additional feature requests possible.

like what if

Producing a convincing module is much easier and the best prerequisite for a possible "feature request".

Cheers Rolf
(addicted to the Perl Programming Language and ☆☆☆☆ :)
Je suis Charlie!

Replies are listed 'Best First'.
Re^2: Feature Idea: qr//e
by LanX (Saint) on Jan 18, 2017 at 15:19 UTC
    Having your other post in mind I misread your question, sorry.

    you don't want to operate on an array but a code-block

    Would you accept something like the following as sufficiently equivalent?

    sub qre(&;@) { my $block = shift; my $str = $block->(@_); return qr/$str/; }

    (not tested)

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

    udpate

    some functional code:

    use Data::Dump; sub qre(&;@) { my $block = shift; my $str = $block->(@_); return qr/$str/; } sub ored { return join '|', map {quotemeta} @_ } sub oredraw { return join '|', @_ } my @strings = qw/. | %/ ; dd qre {join '|', map {quotemeta} @strings }; dd qre \&ored, @strings; dd qre \&oredraw, @strings;

      Hi LanX,

      sub qre(&;@) { my $block = shift; my $str = $block->(@_); return qr/$str/; }

      Thanks, that's an excellent piece of inspiration! Just to take that idea a little further and add support for /i and the like:

      sub qre (&;$) { my $re = shift->(); eval 'qr/$re/'.(shift//'') || die $@ } my $regex = qre{ join '|', qw/foo bar/ }'i'; print "$regex\n"; __END__ (?^i:foo|bar)

      Not that I'm going to start using this right away, for now this is just to satisfy my curiosity ;-)

      Thanks,
      -- Hauke D

        One extra tweak to the prototype would allow you to add trailing modifiers without requiring the pesky quotes around them:
        sub qre (&;*) { my $re = shift->(); eval 'qr/$re/'.(shift//'') || die $@ } my $regex = qre{ join '|', qw/foo bar/ }i; print "$regex\n"; __END__
        or, from Perl 5.20 onwards:
        sub qre :prototype(&;*) { my $re = shift->(); eval 'qr/$re/'.(shift//'') || die $@ } my $regex = qre{ join '|', qw/foo bar/ }i; print "$regex\n";
        Damian