in reply to How to Save a variable outside of a loop
Just to clarify ... there are, basically, two errors at work here:
The first error is that variables are declared inside the loop, that need to be declared outside. Local-variables within a scope (such as “the scope of a while loop”) will be re-initialized each time. Thus, the value from previous iterations are not retained.
The second error is a little bit more subtle, since it is a logic error: during the first iteration of the loop, (by definition) there is no “previous record” to be compared against. Variables such as $prev_1 and $prev_p, therefore, will be undefined. There are many ways to check for this and to handle it ... as long as you do. The defined() function, for example, will check for undef. Therefore, yet-another way to handle this case (in the present program), is to enclose the current if-statement within another if that tests whether (say...) $prev_1 is defined.