AvremyC AvremyC - 5 months ago 32
Perl Question

regex closest match digits

I have a list of numbers

4

44

4420

44208

442082

4420820

44208202

4420820205

44208202057

442082020579

now I have the number 442082020987 , how can i get a regex search to find the closest match?

44?2?0?8?2?0?2?0?5?7?9? gives me all of them , is there a way to show the closest match?

thanks

Answer

I think this is a case for nmin_by from the List::UtilsBy module

use strict;
use warnings 'all';
use feature 'say';

use List::UtilsBy 'nmin_by';

chomp( my @data = <DATA> );

my $target = 442082020987;

say nmin_by { abs($_ - $target) } @data;

__DATA__
4
44
4420
44208
442082
4420820
44208202
4420820205
44208202057
442082020579

output

442082020579

If you would prefer to avoid using the module then this will do job. The output is identical to the first solution

for my $n ( @data ) {
    my $delta = abs($n - $target);
    unless ( defined $min_delta and $min_delta <= $delta ) {
        ($nearest, $min_delta) = ($n, $delta);
    }
}

say $nearest;
Comments