in reply to Understanding alternation

For the sake of performance, you should switch REGEX alternation with short-circuit alternation:

my $text = 'The dog is black cat is white and the fox does not like th +e cow or pig'; print 'match found', "\n" if ( $text =~ /dog/ || /cow/ || /pig/ );

This works fine for simple patterns like you're using. The Camel books has a nice explanation for that in Common Pratices chapter.

Alceu Rodrigues de Freitas Junior
---------------------------------
"You have enemies? Good. That means you've stood up for something, sometime in your life." - Sir Winston Churchill

Replies are listed 'Best First'.
Re^2: Understanding alternation
by Limbic~Region (Chancellor) on Feb 03, 2006 at 16:01 UTC
    glasswalk3r,
    Your code doesn't do what you think it does. You are saying if $text contains dog or $_ contains cow or $_ contains pig. This can be solved 1 of 2 ways.
    local $_ = 'The dog is black cat is white and the fox does not like th +e cow or pig'; print "match found\n" if /dog/ || /cow/ || /pig/; # or by explicitly stating print "match found\n" if $text =~ /dog/ || $text =~ /cow/ || $text =~ +/pig/;
    It is worth noting that alternation in regexen can be expensive but demerphq's patch to bleed perl (and hopefully the recently released 5.8.8) can make it much less so.

    Update: At bobf's request, I am adding the following note as FYI.
    The binding operator =~ has a higher precedence than || so /dog/ is seen by itself. Perl's do what you mean (DWYM) attitude allows that to be a valid expression by assuming you meant the binding operator with the default variable $_. See perlop for more information on operator precedence and perlvar for more info on variables.

    Additionally, The order in which place the alternation should represent the order the items are most likely to appear. This is because the || short-circuits when it knows at least 1 condition is true. Use && when you want all conditions to be met. Since perl, like math, uses precedence in order to know which order things should be evaluated - be sure to read up in perlop. There are lower precedence versions of || and && (or, and) but nothing higher than that of the binding operator.

    Cheers - L~R