in reply to Re: Detect Two Strings in File
in thread Detect Two Strings in File

Sorry to clarify, they absolutely can appear on the same line or may appear on a newline. The only conditions set forth is only the LAST found "string1" needs to be detected. Then from that point foward, find "string2", ignoring everything prior to "string1". If "string2" is not found ON ANY LINE (same or new), yell something.

Let me test through a few scenarios and see if I can clarify further.

After testing your solution here this does indeed seem to be on the right track. It grabbed the last string1 found and then alerted when it found string2. Oddly enough string2 was found on two different lines, but it detected it on the 2nd line, not the first found.

Testing to see if it can be tailored to also detect if on same line

UPDATE - Looks like we can add this condition if it appears on the same line by adding this condition in the failure part:

if ($first_pos == $second_pos) { print "Success! (STRING: $first_pos matches same line as MAGIC : $ +second_pos)"; }
So this SHOULD work. Thanks again for the assistance

Replies are listed 'Best First'.
Re^3: Detect Two Strings in File
by CountZero (Bishop) on Nov 07, 2014 at 05:03 UTC
    Yes, that will work if both strings are found on the same line, but does not guarantee that the second string comes after the first string.

    I have amended my program to take care of this:

    use Modern::Perl '2014'; my $first = qr/STRING/; my $second = qr/MAGIC/; my $first_pos; my $first_sub_pos; my $second_pos; my $second_sub_pos; while (<DATA>) { do { $first_pos = $.; $first_sub_pos = $-[0] } if /$first/; do { $second_pos = $.; $second_sub_pos = $-[0] } if /$second/; } if ( $first_pos and $second_pos > $first_pos ) { say "Success! STRING at $first_pos followed by MAGIC at $second_po +s"; } elsif ( $first_pos and $second_pos == $first_pos and $second_sub_pos > $first_sub_pos ) { say "Success! STRING (char: $first_sub_pos) followed by MAGIC (char: $seco +nd_sub_pos) at $first_pos"; } else { say "Failure! (STRING: $first_pos / $first_sub_pos - MAGIC: $second_pos / +$second_sub_pos)"; } __DATA__ First line second line here is the STRING empty text the STRING again! followed by the MAGIC word more emptiness Oh no! the first STRING again sadness did we look in vain? Ah, STRING and MAGIC success MAGIC and STRING failed
    Just add and delete the last lines of the DATA section to see the various possibilities.

    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