« Where am I? | Main | Sur le Continent »

June 12, 2007

Commenting a Perl Regular Expression

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 $1
                -?
                (\d{3})         # capture digits to $2
                \b
                /gx             ) {
           print "Yes, $2, $1\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.

Posted by gje at June 12, 2007 11:37 PM

Comments

Post a comment




Remember Me?


Well House Consultants Ltd. Copyright 2008