Chamara Keragala Chamara Keragala - 1 year ago 56
Linux Question

Finding missing numbers in a list in Perl

For instance, given ( 1, 2, 5, 6, 7), i'd like to determine that 3 and 4 are missing?

I've found following code which achieves my goal.

use Data::Dumper;
@list= (1,2,5,6,7);
@missing = map $list[$_-1]+1..$list[$_]-1, 1..@list-1;
print Dumper(\@missing);


$VAR1 = [

Can someone please explain the logic behind above code?

Answer Source


Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value composed of the results of each such evaluation.

In your case:

map $list[$_-1]+1..$list[$_]-1, 1..@list-1;

LIST: 1..@list-1: Is a list which contains elements from 1 to 4 (array length-1)

EXPR: $list[$_-1]+1..$list[$_]-1: Uses the index from above (1 to 4) and evaluates expression with range operator.

At each iteration below happens:

$list[1-1]+1..$list[1]-1: 1+1..2-1 = ''
$list[2-1]+1..$list[2]-1: 2+1..5-1 = 34
$list[3-1]+1..$list[3]-1: 5+1..6-1 = ''
$list[4-1]+1..$list[4]-1: 6+1..7-1 = ''
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download