http://www.perlmonks.org?node_id=997479


in reply to Re^4: Order in which grep/map receive elements
in thread Order in which grep/map receive elements

BrowserUk is right, don't use a module to do that if you can do it with one line of code! Grep receives an array a LIST and returns an array a LIST. The returned array will be shorter, but the elements will be added in the order in which they are encountered in the other array.

Imagine you do this:

@array1 = @array2;
The elements in @array1 will be in the same order has in @array2, right?

Now do this:

foreach $element ( @array2 ) { push( @array1, $element ); }
The elements in @array1 will still be in the same order has in @array2, don't you think?

And if you do this:

foreach $element ( @array2 ) { if ( not $seen{$element} ++ ) { push( @array1, $element ); } }
Guess what? The elements will still be in the same order and I just explicitly did what grep do in one line.

There are no stupid questions, but there are a lot of inquisitive idiots.