http://www.perlmonks.org?node_id=1225399


in reply to Copy an hash modifying some selected values

There will be a hatful of ways to approach this. Here's one using Data::DPath presented as an SSCCE:

use strict; use warnings; use Test::More tests => 1; use Data::DPath 'dpathr'; my $home_path = '/home/foo'; my %hash1 = ( key1 => 'relative_path', key2 => { key21 => 'another_relative_path', key22 => '/an_absolute_path', key23 => 'relative_path', }, key3 => '', key4 => 4 ); my %hash2 = ( key1 => "$home_path/relative_path", key2 => { key21 => 'another_relative_path', key22 => '/an_absolute_path', key23 => "$home_path/relative_path", }, key3 => '', key4 => 4 ); my @list = ('/key1', '/key2/key22', '/key2/key23'); for my $keypat (@list) { foreach my $elem (dpathr ($keypat)->match (\%hash1)) { $$elem =~ s#^(?!/)#$home_path/#; }; } is_deeply (\%hash1, \%hash2);

Replies are listed 'Best First'.
Re^2: Copy an hash modifying some selected values
by Anonymous Monk on Nov 08, 2018 at 09:58 UTC
    Maybe I don't get it but to me this is comparing two hashes instead of searching into a hash a creating a copy of it with modifications where required.

      Quite so. I assumed the copy was not the part you were having problems with. See eg merlyn's deep_copy sub as a module-less way to do that or something like Clone::PP. %hash1 is assumed to be the copy. HTH.