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

I've written some code which calculates how far an animal is from a set location. I want to be able to return the number of animals who are within a certain distance (10km) from the set location. Im using a data file with 300+ animals sorted into Name - Latitude - Longitude. I thought I would create a counter for this, which would increment by 1 when the program found an animal which was within the 10km, but I'm not having any luck with that. (E.g. along the lines of "if $Dist < 10, ++counter" Here's my code so far:
$Mam = 'Mammal.txt'; open(FILE, $Mam) or die "Error. Could not open '$Mam'."; while(<FILE>) { chomp; @Loc = split(/\t/, $_); my $Dist; $Dist = CalculateDistance(54.988056, -1.619444, $Loc[1], $Loc[2]);
The formatting is terrible at the moment since I'm just playing with it. I havn't included the CalculateDistance subroutine as it is quite long, but I can if it will help. I tried
while($Dist < 10) { $counter++; print "$counter animals are found withing 10KM\n" }
but just get the number 0 repeated. The code should be displaying one number which represents the total number of animals found within 10KM of the coordinates provided. I can't see where I'm going wrong.

Replies are listed 'Best First'.
Re: (Beginner) Return number of variables within a set distance.
by toolic (Bishop) on Mar 26, 2015 at 01:38 UTC
    You can increment the count as you read lines from your input file:
    use warnings; use strict; my $cnt = 0; while (<DATA>) { chomp; my ($an, $dist) = split; $cnt++ if $dist < 10; } print "cnt=$cnt\n"; __DATA__ a 50 b 15 c 9 d 11 e 33 f 2

    Prints:

    cnt=2
      That's very useful. Thank you so much!
Re: (Beginner) Return number of variables within a set distance.
by davido (Cardinal) on Mar 26, 2015 at 04:24 UTC

    Please don't remove the content of your nodes. It removes all context for the followups you've received, and makes the thread useless to others who may otherwise search and come up with answers without even having to ask.


    Dave

Re: (Beginner) Return number of variables within a set distance.
by marinersk (Priest) on Mar 26, 2015 at 11:06 UTC

    The other thing that jumps out at me is that you increment the counter inside a set of braces. I do not see a  use strict;. I would be worried that you are dynamically creating, incrementing, and destroying a local copy of  $counter, and then your final print statement is dynamically creating a global copy of  $counter -- which has a value of zero.

    I haven't not used  strict in so long I can't remember the precise behaviors of Perl under those undisciplined parameters.