in reply to headache with arrays.

Hello again Thanks for the help so far. What I actually want to do is the following. I have a text file which looks vaguely like this:
-175 -120 -175 -135
etc ... and what I want to do is to count the number of times that, far example, the first value is within the range -180 to -170 when the second value is within the range -120 to -130. So, in this example, only the top entry is within the required range. I have a number of 'ranges' to look at in the same text file, so I thought it might be a good idea to add all the times a particular value 'set' was within a particular range and then add it to a particular array (appropriately named) and then count them all at the end. Anyway, thats what I thought. If anyone could suggest a good way of tackling this properly, it would be very much appreciated.

Replies are listed 'Best First'.
Re^2: headache with arrays.
by punkish (Priest) on Sep 20, 2004 at 16:40 UTC
    here is a functional program to get you started...

    init a counter open the file and read it line by line split each line on space to get an array of the fvalue and svalue increment the counter if fvalue is within the range AND svalue is with +in the range close the file

    It is really easy so I hope you will find it fun to convert the above into Perl.

    Good luck.

    update: You can even avoid the splitting in line 3 by using a simple regexp to get the fvalue and svalue. Might result in a possible speed increase, and will eliminate one spurious variable creation.

Re^2: headache with arrays.
by jdporter (Paladin) on Sep 20, 2004 at 20:03 UTC
    Unless you need to do something else with all the matches at the end, I'm not sure why you'd save them all in an array. Just count. Example:
    my( $x_lo, $x_hi ) = ( -180, -170 ); my( $y_lo, $y_hi ) = ( -130, -120 ); my $count = 0; while (<>) { my( $x, $y ) = split; if ( $x >= $x_lo && $x <= $x_hi && $y >= $y_lo && $y <= $y_hi ) { $count++; } } print "$count matches.\n";
    If you actually needed the matches, it's simple enough to adapt the above to stick them on an array:
    my( $x_lo, $x_hi ) = ( -180, -170 ); my( $y_lo, $y_hi ) = ( -130, -120 ); my @matches; while (<>) { my( $x, $y ) = split; push @matches, [ $x, $y ] if $x >= $x_lo # slighly different syntax, && $x <= $x_hi # just to mix things up. :-) && $y >= $y_lo && $y <= $y_hi; } print scalar(@matches), " matches.\n";
    And here's a golfish version:
    my( $x_lo, $x_hi ) = ( -180, -170 ); my( $y_lo, $y_hi ) = ( -130, -120 ); my @matches = grep { $_->[0] >= $x_lo && $_->[0] <= $x_hi && $_->[1] >= $y_lo && $_->[1] <= $y_hi } map [ split ], <>;