in reply to Re: how to write a multi-line regex
in thread how to write a multi-line regex

Thanks for the replies. I see it now - I didn't have the /x on the end - or I put it in the $regex (but incorrectly). So either put the /x on the end where it is used in the code or put the whole thing "m/abc/x" in $regex. Ta much.

Replies are listed 'Best First'.
Re^3: how to write a multi-line regex
by johngg (Canon) on Jan 22, 2010 at 11:55 UTC

    If you want to put the x inside the regex you can do it like this (ripping off Utilitarian's code):

    my $regex =qr{(?x) ^(\w*)?\s #A comment (\w*)?\s # an other (\w*)?\s # and again (?:([A-Z]*)\s)? # all the way through (\d+)\* # so that the homicidal psychopath (?:([0-9+]+)[>])? # who knows where you live ([0-9+]+)\s. # and will have to maintain this code (\d*) # will think well of you };

    Note that the (?x) must immediately follow the first regex delimiter otherwise the whitespace before will be a literal part of the pattern (this was not the case with earlier Perl versions, 5.6 IIRC) and note also that using qr{...} creates a compiled regex which you assign to a scalar for later use. The nice thing about the (?x) syntax is the ability to switch behaviours on and off for different regions in your pattern whereas the /.../x modifier applies to the whole pattern. This is probably more useful with something like case insensitivity and such use is illustrated in this reply in a thread started by Win.

    I hope this is helpful.

    Cheers,

    JohnGG

      Thanks John, that's great - the (?x) is a great little trick! I used this technique.