in reply to See if arrays match

Since none of the above code examples quite statisfied me, here's my solution..

# find duplicate entries in array @list my @sorted = sort (@list); my @duplicated; while (@sorted) { my $this = shift (@sorted); if ($this eq $sorted[0]) { push (@duplicated, $this); while (@sorted and $this eq $sorted[0]) { shift (@sorted); } } }

There is potential to shorten up this code and make it more obfuscated, but for learning purposes this should be alright..

Regards,
-octo

Replies are listed 'Best First'.
Re: Re: See if arrays match
by redsquirrel (Hermit) on Jul 24, 2002 at 01:28 UTC
    Your code returns the following when run with warnings enabled: Use of uninitialized value in string eq at... Here's one way to do avoid the warning:
    while ((my $this = shift @sorted) and @sorted) ...
    The warning occurs on the last iteration after you have shifted out the last element of @sorted.

    --Dave

      Oops, you're right.. I was in the unlucky position that the last element of my test array was a duplicate. In this case there wouldn't appear an error.. However, I think it's easier (to understand, anyway) to just change the condition for the first while to:

      while (@sorted > 1) ...

      Which works, because if there is only one element left, it can't be a duplicate.

      Thanks for pointing this out :)

      Regards,
      -octo