Main Content

Commenting a Perl Regular Expression

Archive - Originally posted on "The Horse's Mouth" - 2007-06-12 23:37:33 - Graham Ellis

The x modifier on the end of a Perl regular expression causes all spaces in the regular expression to be treated as comments (rather than matching exactly). This means that you can lay out your regular expressions much more cleanly.

And wherever you're allowed white space, you can add comments from # to end of line. So the following code (for finding Belgian car registrations in a line of input) is valid:

while ($info = <>) {
        while ($info =~ /
                \b
                ([A-Z]{3})      # capture letters to 
                -?
                (\d{3})         # capture digits to 
                \b
                /gx             ) {
           print "Yes, , \n";
        }
        print "And that's your lot\n";
}


Note that you should NOT use the regular expression terminator (/ in our example) within the comments you add ... and if you REALLY want to match a space, you should now use \s for any space character or \x20 for a single space.