Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

remove but count duplicates in a list 1

Status
Not open for further replies.

tonykent

IS-IT--Management
Jun 13, 2002
251
GB
If I have got a list containing lots of duplicated entries that I want to remove I often use

Code:
while (<DATA>) {
	chomp;
	$line=$_;
     $seen{$line}++;
}
@unique = keys %seen;
foreach $entry(@unique) {
	print "$entry\n";
}

This is quick, short and easy.

However, what if I want to remove the duplicates but record how often each appeared in the original list, so that instead of

item1
item2
item3
item4
etc

I end up with

item1 (4 times)
item2 (2 times)
item3 (once)
item4 (8 times)
etc

Can the above code be amended simply to produce this?


 
Hi

Code:
[b]foreach[/b] [navy]$entry[/navy] [teal]([/teal][navy]@unique[/navy][teal])[/teal] [teal]{[/teal]
    [b]print[/b] [green][i]"$entry[highlight] ($seen{$entry} times)[/highlight]\n"[/i][/green][teal];[/teal]

[gray]# or if you care about the 1->once thing[/gray]
    [b]print[/b] [green][i]"$entry ("[/i][/green][teal],([/teal][navy]$seen[/navy][teal]{[/teal][navy]$entry[/navy][teal]}[/teal][teal]==[/teal][purple]1[/purple][teal]?[/teal][green][i]'once'[/i][/green][teal]:[/teal][green][i]"$seen{$entry} times"[/i][/green][teal]).[/teal][green][i]")\n"[/i][/green][teal];[/teal]
[teal]}[/teal]


Feherke.
 
That's even simpler than I had hoped! Thanks again Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top