将两个十进制值与perl中的特定范围进行比较

时间:2015-05-08 09:22:10

标签: perl decimal

我是Perl的新手。我有两组不同的数组。这两个数组具有十进制值,两者都没有完全匹配,它可能只有+0.5-0.5不同。我尝试过这个程序,它没有用。

@inpt = qw(1003.3965 1036.4392 1037.3843 1045.4459 1101.4259 1107.4253 1118.3928 1191.4904 1320.4855 1420.6291 1440.6921 1562.6698 1742.7587 2084.9137 2248.8761 2337.8865 2628.9931);
@outpt = qw(1191.6017 1101.5336 2629.2865 1742.9336 1036.5726 2338.1574 2249.1057 1440.8222 1440.2074);

foreach $s (@outpt){

    $inc = $s + 0.5;
    $dec = $s - 0.5;

   foreach $p ( @inpt ) {
        if ( $p .. $inc ) {           
            print "$p \t $inc";
        }
        elsif ( $p .. $dec ) {
            print "$p \t $dec";
        }
    }
}

我期待以下输出。 @outpt的{​​{1}}值与1191.6017的{​​{1}}值+0.5-0.5的范围相匹配。

@inpt

2 个答案:

答案 0 :(得分:5)

试试这个:

use strict;
use warnings;

my $limit = 0.5;
my $result = "";

my @inpt = qw(1003.3965 1036.4392 1037.3843 1045.4459 1101.4259 1107.4253 1118.3928 1191.4904 1320.4855 1420.6291 1440.6921 1562.6698 1742.7587 2084.9137 2248.8761 2337.8865 2628.9931);
my @outpt = qw(1191.6017 1101.5336 2629.2865 1742.9336 1036.5726 2338.1574 2249.1057 1440.8222 1440.2074);

foreach my $s (@outpt){
   foreach my $t (@inpt) {
      if($s >= $t - $limit && $s <= $t + $limit) {
          $result .= "$s \t $t\n";
      }
   }
}     
print $result;

答案 1 :(得分:2)

my $limit = 0.5;

my @inpt = qw(1003.3965 1036.4392 1037.3843 1045.4459 1101.4259 1107.4253 1118.3928 1191.4904 1320.4855 1420.6291 1440.6921 1562.6698 1742.7587 2084.9137 2248.8761 2337.8865 2628.9931);
my @outpt = qw(1191.6017 1101.5336 2629.2865 1742.9336 1036.5726 2338.1574 2249.1057 1440.8222 1440.2074);

my @result = map {
  my $p = $_;
  map { "$p \t $_" } grep { abs($p-$_) <= $limit } @inpt;
  # without grep
  # map { abs($p-$_) <= $limit ? "$p \t $_" : () } @inpt;
} @outpt;

print $_, "\n" for @result;

输出

1191.6017    1191.4904
1101.5336    1101.4259
2629.2865    2628.9931
1742.9336    1742.7587
1036.5726    1036.4392
2338.1574    2337.8865
2249.1057    2248.8761
1440.8222    1440.6921
1440.2074    1440.6921