首页 > 解决方案 > Perl 查找另一个数组中存在的一个数组中的缺失元素

问题描述

我有两个 IP 地址数组,我想扫描它们并生成仅存在于 @replyResults 但不存在于 @savedResults 中的第三个项目数组

@savedResults = ("5.6.7.8", "9.10.11.12", "13.14.15.16");
@replyResults = ("1.2.3.4", "5.6.7.8", "9.10.11.12", "13.14.15.16", "17.18.19.20");

即应该产生

( "1.2.3.4", "17.18.19.20 )

有任何想法吗?恐怕我无法让我在网上找到的任何东西解决这个特定的用例。

谢谢

标签: perl

解决方案


这段代码解决了您的要求:

use strict;
use warnings;

my @savedResults = ("5.6.7.8", "9.10.11.12", "13.14.15.16");
my @replyResults = ("1.2.3.4", "5.6.7.8", "9.10.11.12", "13.14.15.16", "17.18.19.20");

# Build an auxiliary hash with the @savedResults items as keys.
my %saved_results_hash = map { $_=>1 } @savedResults;

# Filter the @replyResults array with keys that doesn't exist at hash
my @result = grep { !exists $saved_results_hash{$_} } @replyResults;

# <- @result contains: 1.2.3.4, 17.18.19.20

推荐阅读