Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks!

How could I combine or merge these two arrays based on if $ar_ref_1->[1] AND $ar_ref_2->[0] match, thanks or the help!

use strict; use warnings; use Data::Dumper; my $ar_ref_1 = [ [ 'USER 1', '12345', '2009', 'X', '0', '8.00', ' ', '1- E' ], [ 'USER 3', '1234567', '2009', 'X', '0', '8.00', ' ', '3- E' ], [ 'USER 2', '123456', '2009', 'X', '0', '8.00', ' ', '2- E' ], [ 'USER 5', '123456789', '2009', 'X', '0', '8.00', ' ', '5- E' ], [ 'USER 4', '12345678', '2009', 'X', '0', '8.00', ' ', '4- E' ], ]; my $ar_ref_2 = [ [ '1234567', '12', '0', '2', '0', '0', '0', '0', '0', '0', '0', '0' ], [ '123456789', '0998', '2', '2', '3', '0', '0', '0', '0', '0', '0', '0' ], [ '123456', '657', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' ], [ '12345678', '8754', '0', '2', '0', '0', '0', '0', '0', '0', '0', '0' ], [ '12345', '876', '1', '2', '3', '0', '0', '0', '0', '0', '0', '0' ], ]; for my $i (0..$#$ar_ref_1) { for my $j (0..$#$ar_ref_2) { if($ar_ref_1->[1] == $ar_ref_2->[0]){ push @{$ar_ref_1->[$i]} +, @{ ref($ar_ref_2->[$i]) eq 'ARRAY' ? + $ar_ref_2->[$i] : [('-') x 3] }; } } } print Dumper $ar_ref_1;

Here is what I am trying to get, I am sampling one element as an example:
[ 'USER 4', '12345678', '2009', 'X', '0', '8.00', ' ', '4- E' '12345678', # I need to exclude the duplicated element out + as well, it’s a nightmare! '8754', '0', '2', '0', '0', '0', '0', '0', '0', '0', '0' ],

Thank you!

Replies are listed 'Best First'.
Re: Compare and merge array elements help!
by ikegami (Patriarch) on May 07, 2009 at 15:58 UTC
    my %lkup = map { $_->[0] => $_ } @$ar_ref_2; for (@$ar_ref_1) { my $key = $_->[1]; if (my $extra = $lkup{$key}) { push @$_, @$extra[ 1..$#$extra ]; } else { warn("Bad join for $key\n"); push @$_, (undef)x11; } }
      Hi, can't get your code to work with this, here is what I am getting:
      Global symbol "$extra" requires explicit package... Global symbol "$extra" requires explicit package... syntax error near "}" syntax error near "}" Execution aborted due to compilation errors.
        There was a missing ")". Fixed.
Re: Compare and merge array elements help!
by rir (Vicar) on May 08, 2009 at 13:30 UTC
    my %users = map { $_->[0], $_->[1,-1] } @$ar_ref_2; my @answer = map { [@$_, $users{$$_[1]} ] } @$ar_ref_1;

    Be well,
    rir