in reply to How to combine these 2 subroutines in one?
The subroutine needs some way of knowing (or, at least, guessing) whether it has been passed an array or an array reference.
First thought is to test whether the first argument is an array reference:
if (ref($_[0]) eq 'ARRAY') ...See ref. The problem with that approach is that it won’t work if the array passed into the subroutine happens to have an array reference as its first element.
A better approach is to test whether the subroutine is called in list context:
my @array_with_duplicates = wantarray ? @_ : @{ $_[0] };See wantarray. If the sub is called in list context (i.e., the caller is expecting it to return a list), then from the specification we can assume the array was passed in as a list. Otherwise, we assume the array was passed in as a reference.
Here is how I would solve the problem:
#! perl use strict; use warnings; use Data::Dump; my @array; while (<DATA>) { chomp; push @array, $_; } dd \@array; @array = clean(@array); # or clean(\@array); dd \@array; sub clean { my @array_with_duplicates = wantarray ? @_ : @{$_[0]}; my (@array_no_duplicates, %hash); for (@array_with_duplicates) { unless (exists $hash{$_}) { push @array_no_duplicates, $_; $hash{$_} = undef; } } return @array_no_duplicates if wantarray; @{ $_[0] } = @array_no_duplicates; } __DATA__ Frieda Adele Briony Hermione Cathy Dorothy Cathy Erin Ida Frieda Frieda Gertrude Hermione
Output:
22:14 >perl 890_SoPW.pl [ "Frieda", "Adele", "Briony", "Hermione", "Cathy", "Dorothy", "Cathy", "Erin", "Ida", "Frieda", "Frieda", "Gertrude", "Hermione", ] [ "Frieda", "Adele", "Briony", "Hermione", "Cathy", "Dorothy", "Erin", "Ida", "Gertrude", ] 22:14 >
Note: this approach does not rely on sorting the list, but outputs the no-duplicates version in its original order. The specification as given does not mention sorting.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to combine these 2 subroutines in one?
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 | |
by Athanasius (Archbishop) on Apr 04, 2014 at 08:55 UTC | |
|