> -----Original Message-----
> From: Wagner Jeff Civ Logicon/TTMS
> [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, August 01, 2001 2:14 PM
> To: Bob Showalter
> Cc: '[EMAIL PROTECTED]'
> Subject: RE: check array element (HELP)
> 
> 
> Let me see if I understand your one-liner...
> 
> *  the "map" function creates a hash, using the array 
> elements as key names,
> automatically eliminating duplicates
> *  the output from the "keys" function (an array) is compared to the
> original array, both in scalar context, so the number of 
> elements will be
> different if there were duplicates

Yep, you've got it. Actually map() is creating a *list*, which is being used
to initalize an anonymous hash. Working from the inside out:

   map { ($_ => 1) } @arr    

returns a list equivalent to ($arr[0], 1, $arr[1], 1, $arr[2], 1, ...). 
Wrapping any list in curly braces:

   { list }

returns a reference to an anonymous hash initialized from the list. The hash
keys
end up being the (unique) original array values, and each hash entry is
simply
a 1 (which is really being ignored). The notation:

   keys %{ hashref }

returns a list of the keys in the hash pointed to by the hash reference.
Since this expression appears as part of a != test, it is evaluated in
scalar context. Any list evaluated in scalar context returns the number of
elements in the list. So this is equal to the number of unique values from
our original array. We then compare this to @arr, again in scalar context.

So the test is:

   No. of unique elments != No. of total elements

If they are not equal, there must be at least one duplicate.

> 
> Pretty neat.  So the difference between this an the iterative 
> approach is
> that the one liner processes all the array elements every time and the
> iterative approach drops out as soon as it finds a duplicate.

Yes, and my one-liner is almost certainly more memory-intensive than the
iterative approach.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to