OK, let me try again. If I do this on perl 5.14+:
use 5.010;
open my($fh), ">", "out";
my $re = qr/a/;
say $fh "use 5.010; if ('a' =~ /$re/) { say 'match' } else { say 'no match' }";
Then out will contain:
use 5.010; if ('a' =~ /(?^:a)/) { say 'match' } else { say 'no match' }

This code won't run on perl 5.12 or lower due to unknown regex sequence (?^...), which is introduced in perl 5.14. When run on perl 5.12 or perl 5.10, it will print this error message:

Sequence (?^...) not recognized in regex; marked by <-- HERE in m/(?^ <-- HERE :a)/ at out line 1.

I want a code generator that, even though run from perl 5.14+, can generate code that runs on perl 5.12 and lower. So basically I now need to do something like this:

use 5.010;
use re qw(regexp_pattern);
open my($fh), ">", "out";
my $re = qr/a/;
my ($pat, $mod) = regexp_pattern($re);
say $fh "use 5.010; if ('a' =~ /(?$mod-)$pat/) { say 'match' } else { say 'no match' }";
Note that I left out the part where I need to: 1) remove or complain about regex modifiers that are new in 5.14+ and unrecognized in older perls; 2) escape slashes in pattern. But the main point is there.

UPDATE: I'm packaging the routine as a CPAN module: Regexp::Stringify


In reply to Re^4: Dumping regexp for Perl versions earlier than 5.14 by perlancar
in thread Dumping regexp for Perl versions earlier than 5.14 by perlancar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.