linux - Finding missing numbers in a list in Perl -


for instance, given ( 1, 2, 5, 6, 7), i'd determine 3 , 4 missing?

i've found following code achieves goal.

#!/usr/bin/perl use data::dumper; @list= (1,2,5,6,7); @missing = map $list[$_-1]+1..$list[$_]-1, 1..@list-1; print dumper(\@missing); 

output:

$var1 = [           3,           4         ]; 

can please explain logic behind above code?

map expr,list

evaluates block or expr each element of list (locally setting $_ each element) , returns list value composed of results of each such evaluation.

in case:

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

list: 1..@list-1: list contains elements 1 4 (array length-1)

expr: $list[$_-1]+1..$list[$_]-1: uses index above (1 4) , evaluates expression 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 = '' 

Comments