Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Make a subroutine that removes duplicates from a list. If the list is +passed as an array, then return a clean list. If the list is passed a +s a reference to an array then clean the given array in place.
sub clean_list { my @array_with_duplicates=(@_); my @array_no_duplicates; my $previous = ''; while (scalar @array_with_duplicates > 0) { my $next = shift(@array_with_duplicates); if ($previous ne $next) { push(@array_no_duplicates, $next); $previous = $next; } }
andopen(IN, '<', 'myfile') or die "Could not read file\n"; my @array_with_duplicates = <IN>; close IN; @array_with_duplicates = sort @array_with_duplicates; clean_list(@array_with_duplicates); open(OUT, ">", "myfile.NO_DUPLICATES") or die "Could not create file\n +"; print OUT @array_no_duplicates; close OUT;
sub clean_array { my %hash; @hash{@{$_[0]}}=(); @{$_[0]}=keys %hash; }
open(IN, '<', 'myfile') or die "Could not read file\n"; my @initial_array = <IN>; close IN; clean_array(\@initial_array); open(OUT, ">", "myfile.NO_DUPLICATES") or die "Could not create file\n +"; print OUT @initial_array; close OUT;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to combine these 2 subroutines in one?
by Athanasius (Archbishop) on Apr 03, 2014 at 12:32 UTC | |
by Anonymous Monk on Apr 03, 2014 at 13:31 UTC | |
by Athanasius (Archbishop) on Apr 03, 2014 at 13:45 UTC | |
by Anonymous Monk on Apr 03, 2014 at 14:19 UTC | |
by Anonymous Monk on Apr 03, 2014 at 23:13 UTC | |
| |
|
Re: How to combine these 2 subroutines in one?
by hdb (Monsignor) on Apr 03, 2014 at 12:26 UTC |