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

Hi monks, I am currently using the grep function to extract all numbers between two certain values from an array.
my @new_array = grep {$_ == $first_val .. $_ == $second_val} @old_arra +y;
The problem that in one example $second_val is a signed floating point number like -0.0999999999, however grep matched the number to be 0.0999999999 instead so @new_array now contains different values to what I expected. Is there a different way to do this where I won't encounter this problem??

Cheers!

Replies are listed 'Best First'.
Re: using grep to extract numbers from an array
by jaa (Friar) on Jul 10, 2003 at 10:28 UTC
    I would have tried
    my @new_array = grep {$_ >= $first_val and $_ <= $second_val} @old_arr +ay;

    Does this have the same floating point issue?

Re: using grep to extract numbers from an array
by tommyw (Hermit) on Jul 10, 2003 at 13:01 UTC

    This piece of code is going start grabbing elements when the first value occurs, and stop grabbing them when the second value occurs. It'll return the intervening list, irrespective of the value of those intermediate elements.

    Thus:

    my @old_array=(0, 1, 2, 47, 3); my @new_array=grep {$_==1 .. $_==3} @old_array; print "@new_array\n";
    produces 1 2 47 3

    --
    Tommy
    Too stupid to live.
    Too stubborn to die.

Re: using grep to extract numbers from an array
by flounder99 (Friar) on Jul 10, 2003 at 13:21 UTC
    Are you sure you're using the range operator correctly? Your code will return the elements of @old_array from the occurrence of $first_val until the occurrence of $second_val, inclusive. Whereas a compare like jaa's will return the elements whose values are between $first_val and $second_val.
    use strict; my $first_val = -3; my $second_val = -0.0999999999; my @old_array = <DATA>; print "Range operator\n"; my @new_array = grep {$_ == $first_val .. $_ == $second_val} @old_arra +y; print @new_array; print "\nComparison\n"; @new_array = grep {$_ >= $first_val and $_ <= $second_val} @old_array; print @new_array; __DATA__ -5 -3 7 0.0999999999 -0.0999999999 -2 -6 __OUTPUT__ Range operator -3 7 0.0999999999 -0.0999999999 Comparison -3 -0.0999999999 -2

    --

    flounder