http://www.perlmonks.org?node_id=240323


in reply to Flag variables

In the example given, setting the flag is redundant because the &someaction can be called within the loop itself before 'last' is called.

However there are situations where setting the flag is both useful and perhaps even necessary.

Say you've just opened a file for both reading and writing. You've a loop to read each line in the file and do something to it if certain conditions are met or print the line back otherwise. You can't exit the loop with 'last' because that would cause the file to be corrupted (some entries at the end may not have been written back). In this case, it may be useful to set a flag to remember the state and do something about it when the loop is finished...

Did I make sense? Added this:

Continuing from the above example where you're opening a file for both reading and writing. Say you want to print (on the screen via the browser) an error message because one of the lines contains an error or something. You can't just exit the loop and print the error message because that will interrupt the writing of the file and corrupt it. You need to set a flag to remember the error and display that error when the loop is finished.

Replies are listed 'Best First'.
Re: Re: Flag variables
by Anonymous Monk on Mar 04, 2003 at 14:19 UTC

    You made sense but, if you can set a flag in the loop, you can also call a subroutine in the same place as you were setting the flag, and the subroutine can do what ever you would have done as a result of the flag being set after the loop, so your back to square one.

    That's not to say that there aren't occasions when a flag is necessary, or even just easier, but most times they can be avoided and the code benefits from their avoidance.