Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Merging arrays

by kcott (Chancellor)
on Jun 27, 2013 at 21:53 UTC ( #1041107=note: print w/replies, xml ) Need Help??

in reply to Merging arrays

This code produces the output you want:

$ perl -Mstrict -Mwarnings -E ' use List::MoreUtils qw{pairwise}; $a || $b || 1; use Data::Dumper; my @array = qw( 111 222 333 444 555 888 ); my @array2 = qw( acct1 acct2 acct3 acct4 acct5 acct8 ); my $data = [ pairwise { +{ $a => $b } } @array, @array2 ]; print Dumper $data; ' $VAR1 = [ { '111' => 'acct1' }, { '222' => 'acct2' }, { '333' => 'acct3' }, { '444' => 'acct4' }, { '555' => 'acct5' }, { '888' => 'acct8' } ];

Notes on my code:

  • I've excluded the duplicate acct4 (noted earlier by jeffa).
  • See List::MoreUtils for details on pairwise().
  • $a || $b || 1; stops "used only once" warnings for both $a and $b. Another way to do this would be with no warnings 'once'; but that's less specific and could potentially mask other, unrelated problems (see perllexwarn).
  • The + in front of { $a => $b } indicates to perl that this is a hashref — without it, perl interprets { $a => $b } as an anonymous block.

Notes on your code:

  • In scalar context, @some_array evaluates to the number of elements in @some_array, so my $vals_1 = @{$got1}; will result in $vals_1 having a value of 6 (ditto for $vals_2). This would have resulted in messages about trying to use 6 as an array reference. (It would have been better if you had shown your error messages rather than just saying "... having issues ...".)
  • The output you say you want ($VAR2 = [ ... ];) is an arrayref; however, your code is populating hashes. Take a look at the Perl Data Structures Cookbook. If the output that you indicated you wanted is not correct, please clarify what you do want.
  • In the context of your code, where you use print Dumper %data; you probably want print Dumper \%data; (ditto for print Dumper %hash_of_data;). Take a look at Data::Dumper.

-- Ken

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1041107]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2018-02-25 12:18 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (312 votes). Check out past polls.