⭐ in reply to How do I find if an array has duplicate elements, if so discard it?
Here's a chart:
-----------
small data, unoften updated, order not important
# want simplicity
sub remove_redundant {
my %hdata = map { ($_, 1 ) } @_;
return keys %hdata;
}
Note that you might just want to save things in a hash to begin with (and use "keys %data" whenever you want it as an array).
------------
# small data, often update (more reads than writes)
Keep in a hash and convert to a temp array when needed.
%data{$val} = 1;
for my $el ( keys %data ) { ... }
You can even create an overloaded array object which is really just a hash.
------------
# for large data that's rarely updated
push @data, $val if ! grep { $_ eq $val } @data;
It's a linear search, but if we're talking megs of data here, this is MUCH better than building a----------- # for large data that's often updated. (more reads than writes)It's worth while building an overloaded class that stores the data as a hash..
=-=-=-=-=-=-==-
One possible mechanis for using a hash for the array is the following:
our %hash_cache;
sub hash_array_push {
my ( $hash_name, @vals ) = @_;
for my $val ( @vals ) {
$hash_cache{$hash_name}{$val} = 1;
}
}
sub hash_array_del {
my ($hash_name) = @_;
delete $hash_cache{$hash_name};
}
sub hash_array_getref {
my ( $hash_name) = @_;
# note that the user can more efficiently
# utilize an array-ref than an array.
return $hash_cache{$hash_name};
}
Yes there's an additional function call overhead for these funcs, but you'd have that with just
|
|---|