Skip to content

Instantly share code, notes, and snippets.

@vyuh
Created July 2, 2020 15:17
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 vyuh/8c445ef912c1c665c7d7e881bd171941 to your computer and use it in GitHub Desktop.
Save vyuh/8c445ef912c1c665c7d7e881bd171941 to your computer and use it in GitHub Desktop.
Answer to SO Q62653173
#!/usr/bin/env perl
use strict;
use warnings;
use autodie;
use List::Util;
sub replace_first_keys {
my ( $hash, $replace, $replacement ) = @_;
unshift @$replace, $replacement if exists $hash->{$replacement};
$hash->{$replacement} = {
map { %{ delete $hash->{$_} } }
grep { ( exists $hash->{$_} ) && ( ref $hash->{$_} eq 'HASH' ) }
( List::Util::uniq @$replace )
};
$hash;
}
# REPLACE FIRST KEYS OF $hash LISTED IN @$replace WITH THE KEY $replacement
# POSSIBLE USAGE:
# - `replace_first_keys( \%Hash1, [ 3, 4 ], 300 );` (present use case)
# - `replace_first_keys( \%Hash1, [ 3, 4 ], 2 );` (replacement key exists, older values are overwritten on conflict)
# - `replace_first_keys( \%Hash1, [ 3, 4 ], 4 );` (replacement also in replace list, handles this properly)
# TODO ANSWER https://stackoverflow.com/q/62653173/1921546
use Data::Dumper;
my %Hash1;
$Hash1{1}{12} = 1;
$Hash1{1}{10} = 1;
$Hash1{2}{31} = 1;
$Hash1{3}{52} = 1;
$Hash1{3}{58} = 1;
$Hash1{4}{82} = 1;
$Hash1{4}{154} = 1;
print Dumper( \%Hash1 );
replace_first_keys( \%Hash1, [ 3, 4 ], 300 );
print Dumper( \%Hash1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment