http://www.perlmonks.org?node_id=510722

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

Hi there
I have a number of text files that look like something like this
0.2430 0.0830 0.1320 0.0920 0.0180 0.0880 0.3440
I would like to read though this text file and extract the two largest numbers .. in this case, 0.2430 and 0.3440. I've written the following script with this task in mind.
#!/usr/bin/perl $file = $ARGV[0]; open(FILE, "$file") || die "Error, can't open $file file: $!\n"; @input = <FILE>; $largest_value = 0; $second_value = 0; for($i = 0; $i < @input; $i++) { $value = substr($input[$i], 0, 6); if($value > $largest_value) { $largest_value= $value; } if(($value > $second_value) && ($value < $largest_value)) { $second_value = $value; } } print "$largest_value $second_value\n";
The program prints the largest value correctly, but selects 0.1320 rather than 0.2430 for the second largest value, which obviously isn't correct.
Any suggests as regards to what I am doing wrong much appreciated. Thanks.