Created
April 24, 2012 09:19
-
-
Save Cside/2478189 to your computer and use it in GitHub Desktop.
uniq by coderef
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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