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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |