drodinthe559 has asked for the wisdom of the Perl Monks concerning the following question:

Any suggestions on how to declare a variable in a loop without overwriting it. I have to go through this report and pull data off of each line. So, if I store the data in variable and goes through the loop again, it re-initializes my variable.
open TESTFILE, "Y:/Perl Projects/TEST" or die "Couldn't open Test Repo +rt file: $!"; my ($variable1, $variable2); my @return_details, while (my $test = <TESTFILE>) { #if i delcare the variable here it will re-inialize it next tim +e it loops through to an undef. next if ($returns =~ m/^(\s)*$/); print $returns; if (substr($test , 80, 26) =~ m/1ST VARIABLE/) { $variable1 = substr($returns, 113, 18); next; }; if (substr($test , 80, 25) =~ m/2ND VARIABLE/) { $variable2 = substr($test, 113, 18); $rt_flg = 1; }; if ($rt_flg eq 1) { push @return_details, { variable1 => $variable1, variable2 => $variable2 }; $rt_flg = 0; }; };

Replies are listed 'Best First'.
Re: Declare Variable in Loop
by ikegami (Patriarch) on Mar 26, 2010 at 22:22 UTC

    Putting their declaration in the loop body limits their scope to the loop pass.

    Maybe you should tell us what you want to do rather than telling us how you want to do it. My only guess is that you want

    { my ($variable1, $variable2); my @return_details; while (my $test = <TESTFILE>) { ... } }
      I'm trying to remove them as variable since they are only temporary.
        I presume that means that you don't want them accessible by code further down. The solution I presented solves exactly that problem.
Re: Declare Variable in Loop
by ikegami (Patriarch) on Mar 26, 2010 at 22:29 UTC

    state variables actually fit the bill. The downside is that they are never implicitly cleared. A non-obvious side-effect is that it makes the code non-reentrant.

    Note that using them in this circumstance will have the maintainers scratching their head.

    Note that state doesn't fulfill your newly stated goal as it actually increases the scope of the variables to future calls of the same block.

    Update: Added last para in response to new information.

Re: Declare Variable in Loop
by Anonymous Monk on Mar 26, 2010 at 21:59 UTC
    It can't be done.