From: drieux <[EMAIL PROTECTED]>
> On Monday, April 22, 2002, at 09:29 , David Gray wrote:
>
> >> Can anyone tell me the best method for removing duplicate
> >> array values.
> >>
> >> eg:
> >>
> >> @array = qw( a a a b b b c);
> >>
> >> becomes after some operation I cant seem to figure:
> >>
> >> @new_array_or_same = (a b c);
> >
> > In this situation, I usually use a hash instead of an array so I can
> > create highly useful statistics of how often each value occurs.
>
> good reason to not use an autonomous hash.....
>
>
> what I just learned would solve the problem would be
>
> my @array = qw( a a a b b b c);
> my @new_array = keys %{{ map { $_ => 1 } @array}};
>
> since the perldoc -q uniq that jeff provided pokes in
> that direction - but was 'hash' oriented.....
Yes you can do that. But it's slow ...
my @array = qw( a a a b b b c);
my @new_array;
{ my %h; @h{@array} = (); @new_array = keys %h; }
using a named lexical hash and hash slice instead of map is
quicker:
Benchmark: timing 20000 iterations of Faq, Mine...
Faq: 10 wallclock secs ( 9.62 usr + 0.00 sys = 9.62 CPU)
@ 2078.35/s (n=20000)
Mine: 1 wallclock secs ( 1.57 usr + 0.00 sys = 1.57 CPU)
@ 12722.65/s (n=20000)
#!perl
use Benchmark;
@array = ((qw( a a a b b b c d d d f f u u u u u i i a y s e t x)) x 10);
sub Mine {
my @new_array;
{ my %h; @h{@array} = (); @new_array = keys %h; }
return scalar(@new_array);
}
sub Faq {
my @new_array = keys %{{ map { $_ => 1 } @array}};
return scalar(@new_array);
}
timethese 20000, {
Mine => \&Mine,
Faq => \&Faq,
};
__END__
> and, ok, so I am working out the questions:
>
> So why Exactly do I want to have 'map' to begin with?
map { $_ => 1 } @array
creates a list in form:
( $array[0] => 1, $array[1] => 1, $array[2] => 1, ...)
If you then create a hash out of this list, the $array[x] items
become keys and the 1s become values.
So
1. map { $_ => 1 } @array
creates list of keys and values
2. {map { $_ => 1 } @array}
creates a reference to an anonymous hash
3. %{{map { $_ => 1 } @array}}
dereferences the reference
4. keys %{{map { $_ => 1 } @array}}
returns a list of keys.
Jenda
=========== [EMAIL PROTECTED] == http://Jenda.Krynicky.cz ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain
I can't find it.
--- me
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]