Chamara Keragala - 1 year ago 39

Linux Question

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.

`#!/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 someone please explain the logic behind above code?

Answer Source

map

EXPR,LISTEvaluates 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 = ''
```