views:

268

answers:

2

How do you put comments inside a Perl regular expression?

+11  A: 

Use the /x modifier:

my $foo = "zombies are the bombies";
if ($foo =~ /
             zombie  # sorry pirates
            /x ) {
    print "urg. brains.\n";
}

Also see the first question in the perl6faq.

Also it wouldn't hurt to read all of perlre while you're at it.

Eric Johnson
ie "use the /x modifier"
Jesse Rusak
I should vote you down for beating me by <i>that</i> much, but I have to vote you up for the clever example.
Telemachus
You can go ahead and vote me down. I cheated anyway.
Eric Johnson
Cheated? Posted an empty answer, then filled it in, to get that low timestamp? I can't think of anything else that could be called cheating.
ysth
He did ask the question!
Jesse Rusak
Yeah - well, the whole "down-vote" think was a joke anyhow. I just hate when I'm midway through a clever example, and then I see that "New answers posted" flash area at the top of my browser. It's that "Newman!" moment.
Telemachus
Well I had the question and then I found the answer and I figured other people probably have this question too. And its not too immoral since I don't get any reputation for anything unless someone votes me up.
Eric Johnson
you should use { } for multiline for clarity IMO.
Kent Fredric
I use `{}` so that my editor will indent for me.
Brad Gilbert
+10  A: 

Even without the /x modifier, you can enclose comments in (?# ... ):

my $foo = "zombies are the bombies";
if ( $foo =~ /zombie(?# sorry pirates)/ ) {
    print "urg. brains.\n";
}
ysth
The one problem I have with this style is that it can be tough on the eyes. Spaces before or after (?# comment) matter unless you add the /x modifier, in which case, I'm back to the /x modifier anyhow.
Telemachus