Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Merging arrays

by kcott (Abbot)
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


Comment on Re: Merging arrays
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1041107]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (15)
As of 2014-11-27 09:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (183 votes), past polls