SPUG: Fw: Uniq in perl

Jim Flanagan jimfl at colltech.com
Sat Mar 17 14:52:37 CST 2001


The most concise way is to make a hash with each of the elements of the list
as keys, like this:

for (@list) { $uniq{$_} = 1; }
@uniq = keys %uniq;

Alternatively, if you want to emulate the behavior of 'uniq -c' (which
counts the number of occurrances, you can do:

for (@list) {$occurances{$_}++;}


on 5/16/01 5:28 PM, Richard Anderson at Richard.Anderson at raycosoft.com
wrote:

> Does anyone have comments for Mike?
> 
> Richard Anderson, Ph.D.          www.unixscripts.com
> Perl / Oracle / Unix                Richard.Anderson at raycosoft.com
> Raycosoft, LLC                        Seattle, WA, USA
> ----- Original Message -----
> From: "Mike" <shivan at ici.net>
> To: "Richard Anderson" <Richard.Anderson at raycosoft.com>
> Sent: Friday, March 16, 2001 2:12 PM
> Subject: Uniq in perl
> 
> 
>> This is something I had sitting around. I didn't write it. Its a subroutine
>> that uniqs an array. I was just wondering if this is the best way to do it
>> or if anyone has any thing better. Thanks
>> 
>> 
>> ## Usage: &uniq( \@ARRAY );
>> sub uniq {
>> my (@uwork, @unew, $uname);
>> @uwork = @{$_[0]};
>> @uwork = sort( @uwork );
>> @unew  = ( shift @uwork );
>> 
>> foreach $uname ( @uwork ) {
>> @unew=( @unew, $uname) if ( $uname ne $unew[ -1 ] );
>> }
>> 
>> @{$_[0]}=@unew;
>> }
 


--
Jim Flanagan          Collective Technologies
jimfl at colltech.com   http://www.colltech.com


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
  Seattle Perl Users Group (SPUG) Home Page: http://www.halcyon.com/spug/





More information about the spug-list mailing list