I got an uninitialized variable error the way you had it so I added the foreach bit here, & also changed the round to int(). I got your idea:
sub is_approximately_an_integer {
foreach my $x ( @zeros ) {
$x = shift;
my $eps = 0.0001;
return abs( $x-int($x) ) < $eps;
}
}
It seems to work ok like that. I guess next is to use the subroutine with $_ inside grep somehow?
my @wants = grep { } values %haystack;
| [reply] [d/l] [select] |
use strict;
use warnings;
use Math::Round qw/round/;
use Data::Dumper;
# function returns 1 if all arguments are integer
# zero otherwise
sub is_approximately_an_integer {
my $eps = 0.0001;
while( my $x = shift ) {
# need to use "round", "int" does not work!
return 0 if abs( $x-round($x) ) > $eps;
}
return 1
}
# some test cases
print "Testing...\n";
print is_approximately_an_integer( 1, 3.99999999, 5 ), "\n";
print is_approximately_an_integer( 1.2, 3.99999999, 5 ), "\n";
print is_approximately_an_integer( 1, 3.99999999, 5.0000001 ), "\n";
print is_approximately_an_integer( 1, 3.99999999, -5 ), "\n";
print is_approximately_an_integer( 1, 3.99999999, -5.1 ), "\n";
print is_approximately_an_integer( 1, 3.99999999, -5.000000001 ), "\n"
+;
print is_approximately_an_integer( 1, -3.99999999, -5.000000001 ), "\n
+";
print is_approximately_an_integer( 1 ), "\n";
print is_approximately_an_integer( 1.5 ), "\n";
# what if we have hash of arrays ?
my %hash = (
"1,2,3" => [ 1, 3.99999999, 5 ],
"1,2,4" => [ 1.2, 3.99999999, 5 ],
"1,2,5" => [ 1, 3.99999999, 5.0000001 ],
# etc
);
# this returns only the arrays but lose keys
print "\nSelected arrays\n";
my @wants = grep { is_approximately_an_integer( @$_ ) } values %hash;
print Dumper( @wants );
# this returns the keys
print "\nSelected keys...\n";
my @wants = grep { is_approximately_an_integer( @{$hash{$_}} ) } keys
+%hash;
print Dumper( @wants );
print "...and the associated array.\n";
# and you can get the arrays as well
print Dumper( @hash{@wants} );
| [reply] [d/l] |