简体   繁体   中英

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

$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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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