Skip to content

Instantly share code, notes, and snippets.

@Cside
Created April 24, 2012 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cside/2478189 to your computer and use it in GitHub Desktop.
Save Cside/2478189 to your computer and use it in GitHub Desktop.
uniq by coderef
#!perl
# Usage: my @uniq_array = uniq_by { $_->{key} } @array;
use strict;
use warnings;
use List::Util q(first);
use List::MoreUtils qw(uniq);
sub uniq_by (&@) {
my ($code, @array) = @_;
my @rets;
my %map;
for my $one (@array) {
local $_ = $one;
my $ret = $code->($one);
push @rets, $ret;
$map{$ret} = $one;
}
my @uniq_keys = uniq @rets;
map { $map{$_} } @uniq_keys;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment