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

I'd like to do a for or foreach loop that grabs every line with matched array element and does something to that line. The array @reqs is not very big but has no consistent pattern and will change. Here is what I have so far:
for ($y=0; $y<@lines;$y+=1) { if (($lines[$y]=~/^\*R_/) && ($lines[$y]!~/BADSTRING/)) { do something; } }
I'd like to add something like: && ($lines[$y]=~/@reqs/) ? but obviously this doesnt work . Thanks in advance.

Replies are listed 'Best First'.
Re: pattern matching an array
by broquaint (Abbot) on Jul 15, 2003 at 15:24 UTC
    I'd like to add something like: && ($lines[$y]=~/@reqs/)
    Then you can use a simple grep like so
    if (($lines[$y]=~/^\*R_/) && ($lines[$y]!~/BADSTRING/) && grep $lines[$y] =~ $_, @reqs)
    This way if $lines[$y] matches any of the strings in @reqs that particular condition will return true. See. grep for more info.
    HTH

    _________
    broquaint

Re: pattern matching an array
by BrowserUk (Patriarch) on Jul 15, 2003 at 15:34 UTC

    If @reqs contains simple string to match the complete line rather than regexes or partial matches, the you could create a hash and do a fast lookup.

    %reqs; @reqs{ @reqs } = (); for( @lines ) { if( /^\*R/ && $_ !~ /BADSTRING/ && exists $reqs{ $_ } ) { # do something } }

    Lots of ifs, but much quicker when they are true.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller

Re: pattern matching an array
by flounder99 (Friar) on Jul 15, 2003 at 19:33 UTC
    If I understand you correctly @reqs is an array of "requirements" that if all are true you want to accept the line? If that is the case you can create a custom subroutine on the fly using eval
    @reqs = qw/foo bar cat/; $reqsub = eval 'sub { ' . (join ' && ', map { '/\\Q' . $_ . '/'} @re +qs) . ' } '; while (<DATA>) { print if &$reqsub; } __DATA__ *R_dog_cat_horse_foo_bar *R_dog_cat_foo *R_dog_cat_horse_bar *R_dog_cat_horse_foo_bar *R_cat_horse_foo_bar __OUTPUT__ *R_dog_cat_horse_foo_bar *R_dog_cat_horse_foo_bar *R_cat_horse_foo_bar

    --

    flounder