How do I add elements from one Perl array that aren't already in the other array?


my @mylist1;

my @mylist2;

What's the quickest way in Perl to insert in mylist2 all elements that are in mylist1 and not already in mylist2 (ABCDE).


my %k;
map { $k{$_} = 1 } @mylist1;
map { $k{$_} = 1 } @mylist2;
@mylist2 = keys %k;


my %k;
map { $k{$_} = 1 } @mylist2;
push(@mylist2, grep { !exists $k{$_} } @mylist1);

Actually - these might be wrong because they don't account for whether duplicates might exist in either of the original lists.

You didn't say in your question whether the lists are supposed to represent sets (which can't contain duplicates) or just plain lists. That you effectively want @mylist2 = @mylist1 U @mylist2 suggests that you are treating them as sets.

EDIT: changed increment to assign - saves a read of the hash value

You could just use the List::MoreUtils module's uniq:

use List::MoreUtils qw(uniq);

my @mylist1;
push( @mylist1, "A" );
push( @mylist1, "B" );
push( @mylist1, "C" );

my @mylist2;
push( @mylist2, "A" );
push( @mylist2, "D" );
push( @mylist2, "E" );

@mylist2 = uniq( @mylist1, @mylist2 );

printf "%s\n", ( join ',', @mylist2 );    # A,B,C,D,E

Need Your Help

Do anyone have a working example of gevent-socketio?

python websocket gevent

All the forks of gevent-socketio in bitbucket and github have examples/ that do not work.

emberjs field validation regex

regex validation ember.js

i have a custom emberjs field like this