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

Hi all - the code is not in its proper format nor am I using proper syntax. I believe my question can be answered with a general representation of my code

my $x=0; for (my$a=0; $a<10; $a++) { open (file); while <my $line = file> { $x++; if ($x==1) { print $header, "\n"; (@keys) = split (/\t/, $line); } else { *Does some filtering as each line is read in* } } }

question: I need to print the header and split the line + store into an array ONCE per iteration. Meaning everytime the for loop iterates, the while loop will be carried out. When the while loop is carried out, I need the first part (the if statement) to execute once, and only once. How would I go about doing this?

Replies are listed 'Best First'.
Re: Reset a vairable inside a for loop inside a while loop
by davido (Cardinal) on Aug 09, 2012 at 19:02 UTC

    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

Re: Reset a vairable inside a for loop inside a while loop
by roboticus (Chancellor) on Aug 09, 2012 at 19:32 UTC

    dkhalfe:

    One way to do it would be to get rid of the if statement altogether. You can instead structure your code like this:

    my $x=0; for (my$a=0; $a<10; $a++) { open (file); # Read the column headers my $line = <file>; print $header, "\n"; my @keys = split /\t/, $line; # Process the data while ($line = <file>) { # The stuff inside the original else clause *Does some filtering as each line is read in* } }

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.