So, if I'm understanding correctly, you need $x to reset to 0 on each iteration of the for loop, is that right? You may actually just need to make better use of the iterator variable that is associated with your for loop.

for my $x ( 1 .. 10 ) { my @keys; open my $file_handle, '<', "$filename$x" or die $!; while( my $line = <$file_handle> ) { if( $x == 1 ) { print $header, "\n"; @keys = split /\t/, $line; } else { # Do something with each line read in. } } }

I'm making some assumptions here: I'm assuming that the reason you're opening the file within the for-loop is so that you can open a different file on each iteration (and I'm specifying that the files are differentiated by a number from 1 through 10). You'll have to modify that as you see fit.

I'm also assuming that you want to retain the contents of @keys through all iterations of the while loop, but allow them to reset upon the next iteration of the for loop.

Update: I see now that you asked a nearly identical question here: Need to reset a variable to zero ??, three days ago. You should probably read perlintro, perlsyn, and perlsub to gain a better understanding and appreciation of Perl's scoping rules for lexical variables. After reading the documents I've linked to, your next questions will be ones that show progress above and beyond your previous questions (unlike the current situation with this question).


Dave


In reply to Re: Reset a vairable inside a for loop inside a while loop by davido
in thread Reset a vairable inside a for loop inside a while loop by dkhalfe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.