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


in reply to Removing certain lines from array

If original order doesn't matter try this approach. Broadly, it indexes the array items by using as key the first word. If an key becomes duplicated the item is removed. In detail it uses a hash where keys are the first word of every line in the array. If it tries to add a hash item that does exist (ie, a duplicated key) it sets the hash value to empty string. Finally it filters the hash values discarding those being an empty string.

my @array = ( "hello 1234 5698 7458", "hi 1457 7459 6214", "good_day 1458", "hi 1258 3658", "good_morning 4758", "hi 1453", ); my %indexedArray; my $key; foreach (@array) { $key = (split())[0]; if ( defined $indexedArray{$key} ) { $indexedArray{$key} = ''; } else { $indexedArray{$key} = $_; } } @array = grep(/.+/,values(%indexedArray));

Replies are listed 'Best First'.
Re^2: Removing certain lines from array
by Loops (Curate) on Jul 30, 2013 at 12:24 UTC
    You should turn warnings on and rerun this script.

    Iterating over the array in reverse will avoid the problem of the loop indices needing adjustment after an element is deleted.

    Update: You changed the script while I was replying. Your description doesn't match now, although I suspect it will in a moment. ;o)

      Sorry Loops, I made some changes before reading your comment. In fact the original script didn't work and I think your comment is not suitable for the new one. Sorry again, newbie behind the wheel :/