Subject: | running_unique list utility function |
I could not find a running unique function anywhere on the net. And this little sub took quite a long time to get all of the edge cases perfected. If you would like, please add it to the List::MoreUtils package. If not I may add it to the List:: namespace separately.
Thanks,
Mike
returns (undef,4,1,2,undef,2,3,undef,,3,2,1,3,1,4,undef)
perl -e '
#Copyright (c) 2013 Michael R. Davis
#License: This library is free software; you can redistribute
#it and/or modify it under the same terms as Perl itself.
use strict;
use warnings;
my @list=running_unique( undef,undef,4,1,1,1,2,
undef,undef,2,2,3,3,undef,"","","",
3,2,2,1,1,3,1,1,1,4,undef,undef);
print join(",", map {defined($_) ? $_ : "undef"} @list), "\n";
sub running_unique {
my $prev=not($_[0]); #very smart initial value
my @list=grep {
my $keep=0;
my $this=$_;
if (defined($prev) and defined($this)) {
$keep=1 if $prev ne $this; #string compare!
} else {
$keep=1 unless (!defined($prev) and !defined($this));
}
$prev=$this;
$keep
} @_;
wantarray ? @list : \@list;
}
'
mrdvt92