sgrey has asked for the wisdom of the Perl Monks concerning the following question:

Hope I have my terms correct - I am looking for syntax to manipulate a slice of a hash_ref of a hash_ref.
What I want to do is replace the values "a" and "b" with "c" and "d" for KEY11 and KEY12, respectively. The code below is as close as I have come. The print Dumper results follow the code.

#!/usr/bin/perl -w use strict; $href->{KEY1}={KEY11=>"a",KEY12=>"b"}; print 'Initial condition for $href->{KEY1}={KEY11=>"a",KEY12=>"b"}'."\ +n"; print Dumper $href; ${$href->{KEY1}}{KEY11}="c"; print 'Change one key in the hash:${$href->{KEY1}}{KEY11}="c"'."\n"; print Dumper $href; @{$href->{KEY1}}{[qw/KEY11 KEY12/]}=("c" ,"d"); print 'Change all keys in the slice:@{$href->{KEY1}}{[qw/KEY11 KEY12/] +}=("c" ,"d")?'."\n"; print Dumper $href;
Results - Initial condition for $href->{KEY1}={KEY11=>"a",KEY12=>"b"} $VAR1 = { 'KEY1' => { 'KEY12' => 'b', 'KEY11' => 'a' } }; Change one key in the hash:${$href->{KEY1}}{KEY11}="c" $VAR1 = { 'KEY1' => { 'KEY12' => 'b', 'KEY11' => 'c' } }; Change all keys in the slice:@{$href->{KEY1}}{[qw/KEY11 KEY12/]}=("c" +,"d")? $VAR1 = { 'KEY1' => { 'KEY12' => 'b', 'ARRAY(0x50db350)' => 'c', 'KEY11' => 'c' } };

I end up with an anonymous array instead of the slice substitution I was looking for. Any help pointing out the correct syntax would be greatly appreciated.

Replies are listed 'Best First'.
Re: HowTo Href_O_Href slice
by LanX (Saint) on Feb 24, 2012 at 20:19 UTC
    If I understand your question correctly, line 106 is what you're looking for.

    DB<105> $href = { KEY1 => { KEY11 => "c", KEY12 => "b" } } => { KEY1 => { KEY11 => "c", KEY12 => "b" } } DB<106> @{$href->{KEY1}}{qw/KEY11 KEY12/}=("c" ,"d"); => ("c", "d") DB<107> $href => { KEY1 => { KEY11 => "c", KEY12 => "d" } }

    you are getting an anonymous array because you enclosed your slice-range in brackets.

    Cheers Rolf

      Thanks Rolf, that did the trick. Much Obliged for your help!

Re: HowTo Href_O_Href slice
by roboticus (Chancellor) on Feb 24, 2012 at 20:16 UTC

    sgrey:

    You do it like this:

    $ cat foo.pl #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $hr = { KEY11=>{a=>1, b=>2, c=>3, d=>4}, KEY12=>{a=>10, b=>20, c=>30, d=>40} }; @{$$hr{KEY11}}{qw(a b)} = @{$$hr{KEY12}}{qw(c d)}; print Dumper($hr);

    which gives you this:

    $ perl foo.pl $VAR1 = { 'KEY12' => { 'c' => 30, 'a' => 10, 'b' => 20, 'd' => 40 }, 'KEY11' => { 'c' => 3, 'a' => 30, 'b' => 40, 'd' => 4 } };

    Update: Oops--I read your question wrong. Oh, well, at least this example shows how to copy a slice of values to a different slice...

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

Re: HowTo Href_O_Href slice
by JavaFan (Canon) on Feb 24, 2012 at 20:15 UTC
    Don't use an arrayref, use a list:
    @{$href->{KEY1}}{qw/KEY11 KEY12/}=("c" ,"d");