Skip to content

Instantly share code, notes, and snippets.

@Kesin11
Created June 25, 2014 23:37
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 Kesin11/d513e3d5ca649541e34c to your computer and use it in GitHub Desktop.
Save Kesin11/d513e3d5ca649541e34c to your computer and use it in GitHub Desktop.
Util.pl
#!/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