develooper Front page | perl.beginners | Postings from August 2009

Seeing if any element of an array is in the current line

Thread Next
From:
Mazza, Glen R.
Date:
August 13, 2009 10:43
Subject:
Seeing if any element of an array is in the current line
Message ID:
D3B0883DB0CAEA469F365D64039BB2550737E76D@0015-its-exmb04.us.saic.com
Hello, I'm trying to write a simple Perl script to output certain lines
from a logfile that contain any of a few phrases.  I have two questions
on the script I've done:

 

use strict;

use warnings;

 

open my $infile, '<', $ARGV[0] or die "Can't open $ARGV[0]";

 

# Put in the badlist words that you want lines containing that

# word to be excluded.

my @goodlist = ("word1", "word2");

 

while ( <$infile> ) {

   foreach my $term(@goodlist) {

      if (/$term/) {

         print;

      }

   }

}

 

1.)  (Major question)  I was wondering if I could get rid of the foreach
and instead use some construct like:

If (/@goodlist/) {...}

 

Meaning "if the current line has *any* of the words in the array..."

 

2.)  (Minor question) The current script has a bug, it will output the
line twice if it contains both words.  I was wondering if the foreach
has some form of "continue" statement that stops the current iteration
of foreach and go to the next one so the line does not output twice.  I
couldn't find anything in the docs for this, though.

 

   foreach my $term(@goodlist) {

      if (/$term/) {

         print;

         continue;   # ???

      }

   }

 

Thanks,

Glen

 


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About