> -----Original Message-----
> From: Jackson, Harry [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, May 15, 2002 12:23 PM
> To: [EMAIL PROTECTED]
> Subject: Optimising for fun/speed not good code was Unique Lists
> 
> 
> Hi
> 
>       sub harryGrep {
>       return [ grep { not $\{$_}++ } @_ ];
>       }
> 
> 
> It took me quite a while to find something quicker than the 
> original grep
> using the function I first tried and then I happened across a 
> piece of text
> talking about return contexts and tried the above. I also 
> noticed a little
> bit of code from Drieux's page's  and tried this and knocked 
> nearly 0.5s off
> it again
> 
> sub unique{foreach (@_) { $_{$_}++} [keys %_]}
> 
> sub GrepMe { [ grep { ! $/{$_}++} @_ ]} 
> 
> I did not know you could drop the return until I seen Drieux 
> do it. Another
> method that is quicker than my foreach attempt is the following.
> 
> sub unique{ map { $_{$_} = 1 } @_;  [keys %_] }
> 
> I would like to have been able to do something like the 
> following but it
> does not work?
> 
> 
> sub unique{ [ keys {map { $_{$_} = 1 } @_ }]  }
                      ^^^^^^^^^^^^^^^^^^^^^^

This returns a list of the results of the block { $_{$_} = 1 }
as evaluated for each value in @_.

But the value of the expression $_{$_} = 1 is always 1, to
your map() is returning a list of 1's. This is obviously
not suitable for converting to a hash to pass to keys().

You probably want:

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

This creates a list of (key, 1) pairs for each element in @_.
So if @_ contains 'foo','bar','baz', the map output list
will be:

   'foo', 1, 'bar', 1, 'baz', 1

Now, you can create a ref to an anonymous hash out of that 
list by:

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

To dereference that to a hash to pass to keys(), you would use:

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

Now the final sub is:

   sub unique { keys %{{map {($_ => 1)} @_}} }

(I removed the square brackets to return a list instead of an
array ref. Your choice.)

> 
> I think the BLOCK {map { $_{$_} = 1 } @_ } returns a 
> reference and it will
> need to be de-referenced for keys to work but I cannot figure 
> it out any
> ideas anyone.

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

Reply via email to