Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: How to Save a variable outside of a loop

by poj (Abbot)
on Jul 31, 2015 at 21:50 UTC ( [id://1137071]=note: print w/replies, xml ) Need Help??


in reply to How to Save a variable outside of a loop

You also need to skip the comparison for the first line of data.
#!/usr/bin/perl use warnings; use strict; my $prev_l; my $prev_p; my $count = 0; ### add while(<>){ my $hitlength; my $prevalence; my $line = $_; chomp $line; if ($line =~ /^[\d]/){ my @hitline = split(/,/ , $line); $hitlength = $hitline[4]; $prevalence = $hitline[65]; if( ($count++) and ($hitlength == $prev_l) and ($prevalence == $prev_p) ){ next; } else { print "$line\n"; } $prev_l = $hitlength; $prev_p = $prevalence; } }
poj

Replies are listed 'Best First'.
Re^2: How to Save a variable outside of a loop
by Laurent_R (Canon) on Aug 01, 2015 at 10:16 UTC
    You also need to skip the comparison for the first line of data.
    Or you could just give an initial dummy value to the two previous variables, thereby saving some steps within the loop:
    #!/usr/bin/perl use warnings; use strict; my ($prev_l, $prev_p) = ("", ""); while(<>){ my $hitlength; my $prevalence; my $line = $_; chomp $line; if ($line =~ /^[\d]/){ my @hitline = split(/,/ , $line); $hitlength = $hitline[4]; $prevalence = $hitline[65]; if( $hitlength == $prev_l and $prevalence == $prev_p ){ next; } else { print "$line\n"; } $prev_l = $hitlength; $prev_p = $prevalence; } }

      That'll yield a warning:

      c:\@Work\Perl\monks>perl -wMstrict -le "my $x = ''; print 'equal' if $x == 1; " Argument "" isn't numeric in numeric eq (==) at -e line 1.


      Give a man a fish:  <%-(-(-(-<

        Yes, AnomalousMonk, you're right, I did not pay attention to the fact that the code is using numeric comparison. I'm doing this type of things regularly, but usually with the string eq operator, even when the data string is numeric (say a customer number or a phone number with only digits). Reducing the number of operations made in the while (<$fh>) loop makes some sense when removing duplicates from a 500-million-line file.

      Apart from the warning, you have to be certain that on the first line of data those 2 fields don't contain the dummy values you initialize to otherwise it will be treated as a duplicate and skipped.


      poj

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1137071]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (5)
As of 2024-03-29 13:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found