As a general thing don't declare variables until you have an initial value for them. The use of prev_l and prev_p is an exception to that guideline where the operation of the code requires the two variables to be declared outside the loop.
Nested blocks generally obfuscate code so try to avoid that. One powerful tool for reducing nesting is to use early exits. Look at the following code and see how next with if as a statement modifier is used to abort processing loop statements wherever there is no need to continue.
Note too the use of defined to handle the first line correctly.
#!/usr/bin/perl use warnings; use strict; my $prev_l; my $prev_p; while (my $line = <DATA>) { next if $line !~ /^[\d]/; chomp $line; my @hitline = split (/,/, $line); my $hitLength = $hitline[4]; my $prevalence = $hitline[65]; next if defined $prev_l && $hitLength == $prev_l && $prevalence == + $prev_p; print "$line\n"; $prev_l = $hitLength; $prev_p = $prevalence; } __DATA__ 23750,57495,78362,xxxx,2853,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,60,100 23751,57497,78364,xxxx,2853,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,60,100 23752,57500,78367,xxxx,3114,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,60,100 23753,57502,78369,xxxx,3114,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,60,100 23754,57504,78371,xxxx,101,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,60,100
Prints:
23750,57495,78362,xxxx,2853,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,60,100 23752,57500,78367,xxxx,3114,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,60,100 23754,57504,78371,xxxx,101,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 +,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, +1,1,1,1,60,100
In reply to Re: How to Save a variable outside of a loop
by GrandFather
in thread How to Save a variable outside of a loop
by Calebros
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |