This would greatly improve the readability of many regular expressions I write, and when I write a single literal space in my regexes I almost always mean \s* anyway. So, is there a "mode" in Perl regular expressions that enables this, like /s to make . match newlines, etc.? A cursory read through perlre didn't give anything, but maybe I missed something or maybe there's a different way to achieve this?
Edit: What I mean is, currently I write qr/^\s*var\s+items\s*=\s*[\s*$/, and I'd instead like to write qr/^ var\s+items = [ $/ and have it mean the same thing using some means- and my question is whether such a means exists.
Here's a sample of using an overload (http://perldoc.perl.org/perlre.html#Creating-Custom-RE-Engines) for your specific substitution.
myre.pm
package myre;
use overload;
sub import {
overload::constant 'qr' => \&spacer;
}
sub spacer {
my $re = shift;
$re =~ s/ /qr{\s*}/ge;
return $re;
}
1;
example.pl
use myre;
print "ok" if "this is\n\n a test" =~ /this is a test/;
Nope, there is no such functionality available. But there is the /x mode that prevents literal space from matching anything at all, so that you can visually structure your regex.
qr/\A\s* var \s* items \s*=\s* \[ \s*\z/x
(except in character classes – [ ] matches a space again).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With