简体   繁体   English

如何在perl中合并两个包含数组引用的数组引用?

[英]How to union two array references containing array references in perl?

Let's say I have an array reference which looks like - 假设我有一个数组引用,看起来像-

my $arrayref1 = [[1,2], [3,4], [5,6]];

and, I have another array reference as - 而且,我还有另一个数组引用为-

my $arrayref2 = [[1,2], [3,4], [7,8]];

How do I achieve something like this - 我如何实现这样的目标-

push @{$arrayref1}, @{$arrayref2};

such that arrayref1 will look like this (excluding array references containing common elements) - 这样arrayref1将看起来像这样(不包括包含公共元素的数组引用)-

$arrayref2 = [[1,2], [3,4], [5,6], [7,8]];

Use a hash of hashes to represent the existing elements of the union: 使用哈希散列表示联合的现有元素:

#!/usr/bin/perl
use warnings;
use strict;

my $arrayref1 = [[1,2], [3,4], [5,6]];
my $arrayref2 = [[1,2], [3,4], [7,8]];

my %set;
undef $set{ $_->[0] }{ $_->[1] } for @$arrayref1;

my @union = @$arrayref1;

for my $pair (@$arrayref2) {
    push @union, $pair unless exists $set{ $pair->[0] }{ $pair->[1] };
    undef $set{ $pair->[0] }{ $pair->[1] };
}

use Data::Dumper;
print Dumper \@union;

This will do as you ask 这将按照您的要求

use strict;
use warnings 'all';

my $arrayref1 = [[1,2], [3,4], [5,6]];
my $arrayref2 = [[1,2], [3,4], [7,8]];

my $result = meld($arrayref1, $arrayref2);

print join (', ', map { sprintf "[%d,%d]", @$_ } @$arrayref1), "\n";

sub meld {
    my ($a1, $a2) = @_;
    my %uniq;

    $uniq{"@$_"} = 1 for @$a1;

    for ( @$a2 ) {
        my $key = "@$_";
        next if $uniq{$key}++;
        push @$a1, [ @$_ ];
    }

    $a1;
}

output 输出

[1,2], [3,4], [5,6], [7,8]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM