How to identify the absence of a term in a file using PERL

Asked

Viewed 28 times

0

Hi, I need some help here. I am writing a perl program that will identify certain patterns in a text file using regex. However, when the search term is not present in the text, I need the program to inform the user. I open the file and save it in a array and walk through it with a bow for. Use if to find my pattern and print it. When I add elsifor else, The program prints for every line he ran that didn’t find the pattern. I needed him to print only when he reached the end of the document if he couldn’t find the pattern. does anyone know how to do that? Maybe with while. Worth the/

for($i=0; $i<=$#report; $i++){
    if($report[$i] =~ /target/){
       chomp $report[$i];
       print "$report[$i]";
    }
    else{
       print "not found\t";
    }
 }

2 answers

2

You can use a variable that records whether the pattern was found. For example:

my $found=0;
for($i=0; $i<=$#report; $i++){
   if($report[$i] =~ /target/){
      chomp $report[$i];
      print "$report[$i]";
      $found=1;
   }
}

print "not found\t" if (!$found);

0

By the way a slightly more cryptic version:

print ( join(";", grep /target/,@report) || "not found\t")

Where:

  • grep /target/,@report gives the list of elements of the report that match;

(Example: grep /33/, (1..300) ---> 33 133 233)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.