SPUG: Fw: Uniq in perl

Scott Blachowicz scott at sabmail.rresearch.com
Mon Mar 19 20:25:08 CST 2001


On Mon, Mar 19, 2001 at 04:54:48PM -0800, Dean Hudson wrote:
> this may make -w complain but:
> 
> @out = grep {!/^$last$/ and $last = $_} @in;
> 
> behaves like uniq; it only gets rid of adjacent duplicated lines.

A couple problems:

1) The $last in the regexp needs to be escaped for use there (e.g.
   with "\Q$last\E" if I remember correctly.
2) That doesn't work if $_ happens to test false (as would happen with
   a blank line if @in were full of chomp()'d lines).

So, something more along the lines of:

   @out = grep {my $x = (defined $last && $last ne $_); $last = $_; $x} @in;

might be the trick (though it's not going to win any perl golf
contests).  Or if you can afford to allocate some extra data for a
list of indices...

  @out = @in[grep {$_ == 0 or $in[$_-1] ne $in[$_]} 0..$#in];

Scott

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     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