in reply to Rename Duplicate List Elements in an Array

I happened to google this problem almost exactly 10 years later only to find this like a message in a bottle to myself in the future! :)

I'd like to make it look a bit nicer:
my @list = qw( one two three one ); @list = make_unique( @list ); sub make_unique { my @list = @_; my %seen; my @new_list; foreach my $item ( @list ) { if ( not defined $seen{$item} ) { $seen{$item} = 1; push @new_list, $item; } else { push @new_list, $item . '_' . $seen{$item}; $seen{$item}++; } } return @new_list; }

Replies are listed 'Best First'.
Re^2: Rename Duplicate List Elements in an Array
by Anonymous Monk on Sep 24, 2015 at 16:02 UTC
    #!/usr/bin/perl use strict; use warnings; my @list = qw( one two three one one two_2 two_2 two two_2 two two_3 t +wo one ); @list = make_unique( @list ); print "@list\n"; sub make_unique { my (%seen, $try); map { my $n = $seen{$_}; $n++ while $seen{$try = $n ? $_ . "_$n" : $_}++; $try } @_; }