【问题标题】:Perl find missing elements in one array present in another array [duplicate]Perl在另一个数组中找到一个数组中的缺失元素[重复]
【发布时间】:2021-08-25 17:31:50
【问题描述】:

我有两个 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 )

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

谢谢

【问题讨论】:

  • 还有perlfaq4
  • 你试过什么?你有什么问题?
  • @dawg:为什么要链接到这样一个特定(和旧!)版本的常见问题解答?
  • @DaveCross:因为那是我记得的,它展示了如何使用数组进行设置计算。

标签: perl


【解决方案1】:

这段代码解决了你的需求:

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

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 2012-06-22
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多