Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Copy an hash modifying some selected values

by hippo (Canon)
on Nov 08, 2018 at 09:31 UTC ( #1225399=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1225399]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2019-02-17 21:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I use postfix dereferencing ...









    Results (98 votes). Check out past polls.

    Notices?