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

I have a loop where I want to check that a certain word is not part of my URLs. But I am having problems with the part where I am trying to make sure my search ignores anything with three specific words in it. For example If a URL has a word called "longwordOne" in it then I dont want it part of my loop search. Here is part of what I have tried:
#words I dont want to be part of my loop search: $wordOne = 'longwordOne'; $wordTwo = 'anotherLongWord'; $wordThree = 'thirdLongHere'; #loop search here next if ($_ =~ /(?:$wordOne|$wordTwo|$wordThree)/gi);

Replies are listed 'Best First'.
Re: next if attempt
by dreadpiratepeter (Priest) on Jul 16, 2003 at 12:57 UTC
    What is your exact issue. I find nothing wrong with the code (besides being needlessly verbose and containing an unneeded /g, see below). The regexp should work as far as I can see. Indeed, it works find on this test program:
    use strict; my $wordOne = 'longwordOne'; my $wordTwo = 'anotherLongWord'; my $wordThree = 'thirdLongHere'; while (<DATA>) { next if ($_ =~ /(?:$wordOne|$wordTwo|$wordThree)/gi); print ; } exit; __DATA__ blah blah longwordOne blah blow blow blee anotherLongWord glgl thirdLongHere fddsf ds sdfs fs fsd fggh hg longwordOne sdasd

    I get:
    blow blow fddsf ds sdfs fs fsd sdasd
    and the next can be written more succinctly as:
    next if /$wordOne|$wordTwo|$wordThree/i;


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."

      To make it a bit easier to update, one might write it as:

      my @stopwords = qw( longwordOne anotherLongWord thirdLongHere ); my $stopmatch = join( '|', @stopwords ); while( <DATA> ) { next if /$stopmatch/i; print; }

      Thus you only have to update the @stopwords array to add another stop-word.

      --
      "To err is human, but to really foul things up you need a computer." --Paul Ehrlich

        and to make it more accurate, one might write it as (untested:)

        my @stopwords= qw/ car pet carpet /; my $stopmatch= join '|' => map { '\b' . $_[1] . '\b' } ## match full words reverse sort { $a->[0] <=> $b->[0] } ## longest first map { [length $_, $_] } @stopwords;

        Thus longer words will match first, and only full words will be matched.

        ~Particle *accelerates*