in reply to Detect Two Strings in File

If you have two things to do, do them as two things. First find the first string, then as a second thing find the second string. Consider:

#!/usr/bin/perl use strict; use warnings; my $str1 = 'through a file'; my $str2 = 'string'; my $lastStr2Line; 1 while <DATA> !~ m/$str1/; m/$str2/ and $lastStr2Line = $. while $_ = <DATA>; die "String 2 '$str2' not found\n" if ! defined $lastStr2Line; print "String 2 last found on line $lastStr2Line\n"; __DATA__ Here's a good one. Looking to read through a file and then detect a ce +rtain string. Then check again sometime later to detect a different string a +nd alert if that different string isn't found. While this string could appear a +nywhere in the file, I would only want the last found string to run this check on +... example:

Prints:

String 2 last found on line 4
Perl is the programming world's equivalent of English

Replies are listed 'Best First'.
Re^2: Detect Two Strings in File
by CountZero (Bishop) on Nov 06, 2014 at 05:19 UTC
    You are not looking for the last possible 'through a file' string! If this string happens a second time, after 'string' happened, your program gives a false positive.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics