Bootstrap FreeKB - Perl (Scripting) - Loop through a file until line match
Perl (Scripting) - Loop through a file until line match

Updated:   |  Perl (Scripting) articles

Let's say you have a file that contains fruit.

apple
banana
orange
pineapple

 

This markup will print lines each line in the file until a line containing "orange" is matched.

my $file = "/path/to/file.txt";

if (-e $file and -r $file and open FH, "<", $file ) {
  while (my $line = <FH>) {
    print $line;
    last if $line =~ /orange/i; 
  }
  close FH;
}
else {
  print "failed to open $file due to the following: $! \n";
  exit 1;
}

 

Running this script will produce the following output.

apple
banana
orange

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter a4247b in the box below so that we can be sure you are a human.