in reply to flag function

using a flag is fine. What you have is completely understandable, however your code will keep reading lines even after the flag is found. I would probably code something similar to what hippo++ did which uses last; to stop the loop once reading more lines has no useful purpose.

However, something like this is also possible if the file is "small":

print "start\n" if (grep {/test/}<TEST>);
This would also read all of the lines in <TEST>. The scalar value of the grep is number lines containing "test". So you get one single print of "start" if any lines contain "test". Not the most efficient way, but also obvious to a Perl'er and fine if the file is "small".

Another loop construct instead of "last" could be:

while (<TEST> and !$flag){} #UPDATE---see below discussion!
I would use something like that if the block of code is more than say 5 lines. Then I see that the loop will stop prematurely without having to read the body of the code and realize that there is a "last;" Of course I would name $flag to something like $test_seen.

Update:
oh, I see now: open TEST,"@ARGV[0]"; that would be flagged as an error if you have use strict; use warnings; in effect. Correct is $ARGV[0].

Replies are listed 'Best First'.
Re^2: flag function
by choroba (Cardinal) on Jul 12, 2018 at 07:23 UTC
    while (<TEST> and !$flag){}

    Just a note: if you want to do something with the line read from the filehandle (and you probably want to set the flag at least), you can't just use <TEST>: it only works in a simple while, not in a more complex condition.

    1 while defined ($_ = <>) and not $seen = /test/; say $seen;

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      You are correct!
      I typed that in quicky from a cut-n-paste of OP's code without actually running a piece of code.

      For those interested, here are some redacted code examples to show what happens:

      while (<DATA> and !$flag){print;} error is: Use of uninitialized value $_ in print at C:\testwhile.pl li +ne 8, <DATA> line 1. while ($_=<DATA> and !$flag){print;} error is: Value of <HANDLE> construct can be "0"; test with defined() +at C:\testwhile.pl line 6. while (defined($_=<DATA>) and !$flag) no error
      I was impressed the first time that I saw error msg #2! Perl tells you exactly what to do and why. Impressive!
      Of course these are examples of why to always use strict; use warnings;!

      Update: A recent post my me that demo's this: Re: Search between pattern and append