Thursday, 15 January 2015

perl - Merge hashes with arrays with Hash::Merge -



perl - Merge hashes with arrays with Hash::Merge -

i trying merge 2 hashes contains 1 or more arrays using hash::merge. example:

use strict; utilize warnings; utilize feature qw(say); utilize data::dump qw(dump); utilize hash::merge qw(merge); $h1 = { => [ { aa => 1 }, 3 ] }; $h2 = { => [ { bb => 2 } ] }; $hleft = merge( $h1, $h2 ); $hright = merge( $h2, $h1 ); " hleft: " . dump($hleft); " hright: " . dump($hright); $hdesired = { => [ { aa => 1, bb => 2 }, 3 ] }; "desired: " . dump($hdesired);

this gives output:

hleft: { => [{ aa => 1 }, 3, { bb => 2 }] } hright: { => [{ bb => 2 }, { aa => 1 }, 3] } desired: { => [{ aa => 1, bb => 2 }, 3] }

how can right output using hash::merge ?

the default behavior merging arrays append them:

sub { [ @{$_[0]}, @{$_[1]} ] },

to different behavior, 1 must utilize hash::merge::specify_behavior.

the next solution left_precedent, , merges arrays element element:

use strict; utilize warnings; utilize feature qw(say); utilize data::dump qw(dump); utilize hash::merge qw(merge); hash::merge::specify_behavior( { 'scalar' => { 'scalar' => sub { $_[0] }, 'array' => sub { $_[0] }, 'hash' => sub { $_[0] }, }, 'array' => { 'scalar' => sub { [ @{ $_[0] }, $_[1] ] }, 'array' => sub { ( $left, $right ) = @_; @merged = @$left; @to_add = @$right; (@merged) { lastly if !@to_add; $_ = hash::merge::merge( $_, shift @to_add ); } homecoming [ @merged, @to_add ]; }, 'hash' => sub { [ @{ $_[0] }, values %{ $_[1] } ] }, }, 'hash' => { 'scalar' => sub { $_[0] }, 'array' => sub { $_[0] }, 'hash' => sub { hash::merge::_merge_hashes( $_[0], $_[1] ) }, }, }, 'my behavior', ); $h1 = { => [ { aa => 1 }, 3 ] }; $h2 = { => [ { bb => 2 } ] }; $merged = merge( $h1, $h2 ); "merged: " . dump($merged);

outputs:

merged: { => [{ aa => 1, bb => 2 }, 3] }

perl

No comments:

Post a Comment