Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

perl

Given:

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

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

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

like image 885
vtbose Avatar asked Nov 27 '08 19:11

vtbose


People also ask

How do I append an array element in Perl?

push(@array, element) : add element or elements into the end of the array. $popped = pop(@array) : delete and return the last element of the array. $shifted = shift(@array) : delete and return the first element of the array. unshift(@array) : add element or elements into the beginning of the array.

How do you add elements to the same array?

By using ArrayList as intermediate storage:Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.

What is dynamic array in Perl?

Perl arrays are dynamic in length, which means that elements can be added to and removed from the array as required. Perl provides four functions for this: shift, unshift, push and pop. shift removes and returns the first element from the array, reducing the array length by 1.


1 Answers

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
like image 133
oeuftete Avatar answered Oct 23 '22 01:10

oeuftete