Created
June 25, 2014 23:37
-
-
Save Kesin11/d513e3d5ca649541e34c to your computer and use it in GitHub Desktop.
Util.pl
This file contains hidden or 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
#!/usr/bin/perl | |
# 便利関数 | |
use strict; | |
use warnings; | |
use utf8; | |
use Clone qw(clone); | |
# arrrefをユニークな$keyごとのhashに変換する | |
# arrref_to_hash [{key => 1, foo => bar},{key = 2, foo => hoge}] | |
# >> {1 => {foo => bar}, 2 => {foo => hoge}} | |
sub arrref_to_hash { | |
my ($arrref, $key) = @_; | |
my $out = {}; | |
my $clone_arrref = clone($arrref); | |
for my $hash (@$clone_arrref){ | |
my $value = $hash->{$key}; | |
$out->{$value} = $hash; | |
delete $out->{$value}->{$key}; | |
} | |
return $out; | |
} | |
my $arrref = [{key => 1, foo => 'bar', a => 'b'}, | |
{key => 2, foo => 'hoge', a => 'c'}, | |
{key => 3, foo => 'foo', a => 'd'}]; | |
my $hash = arrref_to_hash($arrref, 'key'); | |
use Data::Dumper; warn Dumper $hash; | |
use Data::Dumper; warn Dumper $arrref; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment