perlpal has asked for the wisdom of the Perl Monks concerning the following question:

Hi PerlMonks,

I chanced upon this discrepancy in pattern matching behavior. I don't understand the reason for which i seek assistance.

When using multiple alternation meta characters across multiple lines in a single regex , not all the patterns are correctly matched.

The code below does not work

#!/usr/software/bin/perl my $output = "Error: Illegal option -- x"; print "\nTRUE\n" if ( $output =~ /The.*?command\stakes.*?arguments;\syou\sgave.* |Illegal\soption.* |.*?is\snot\sa\svalid\soption.*/i );

whereas the same works when the alternation meta characters are in a single line

#!/usr/software/bin/perl #my $output = `dfm event list -x`; my $output = "Error: Illegal option -- x"; print "\nTRUE\n" if ( $output =~ /The.*?command\stakes.*?arguments;\syou\sgave.*|Illegal\soption +.*|.*?is\snot\sa\svalid\soption.*/i );
Baffled.

Replies are listed 'Best First'.
Re: Alternation metacharacter across multiple lines in regex not working
by Your Mother (Archbishop) on Mar 18, 2010 at 08:12 UTC
    my $output = "Error: Illegal option -- x"; print "\nTRUE\n" if $output =~ /The.*?command\stakes.*?arguments;\syou\sgave.* |Illegal\soption.* |.*?is\snot\sa\svalid\soption.*/ix

    It does now. :)

    Embedded newlines and spaces count unless you use the x.

Re: Alternation metacharacter across multiple lines in regex not working
by GrandFather (Saint) on Mar 18, 2010 at 08:14 UTC

    String like things in Perl allow new lines to be part of the string (unlike many other languages). That is true for double quoted (") and single quoted (') strings and for regular expressions (among others).

    Your "wrapped" regular expression contains white space that is part of the expression to be matched! You can use the /x flag it ignore most white space in your regular expression. Try:

    print "\nTRUE\n" if ( $output =~ /The.*?command\stakes.*?arguments;\syou\sgave.* |Illegal\soption.* |.*?is\snot\sa\svalid\soption.*/ix );

    True laziness is hard work