在Perl的列表中查找缺失的数字 [英] Finding missing numbers in a list in Perl

查看:70
本文介绍了在Perl的列表中查找缺失的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,给定(1,2,5,6,7),我想确定缺少3和4?

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);

输出:

$VAR1 = [
          3,
          4
        ];

有人可以解释上面代码背后的逻辑吗?

Can someone please explain the logic behind above code?

推荐答案

地图 EXPR 列表

计算LIST的每个元素的BLOCK或EXPR (在本地为每个元素设置$ _)并返回列表值 由每次评估的结果组成.

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.

在您的情况下:

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

列表:1..@list-1:是一个包含从1到4(数组长度为1)的元素的列表

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

EXPR:$list[$_-1]+1..$list[$_]-1:使用上面的索引(1到4)并使用范围运算符计算表达式.

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 = ''

这篇关于在Perl的列表中查找缺失的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆