Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re: Removing certain lines from array

by VGavara (Novice)
on Jul 30, 2013 at 11:53 UTC ( #1046999=note: print w/replies, xml ) Need Help??

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 :/

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (2)
As of 2021-09-24 04:17 GMT
Find Nodes?
    Voting Booth?

    No recent polls found