in reply to define a hash-value, using hash-ref and a list of keys

thx for the swift response... much appreciated. learned about some "//=" operator, never seen , but I'm a newbie !! learned the way to construct a hash_ref.... again many thanks...
  • Comment on Re: define a hash-value, using hash-ref and a list of keys

Replies are listed 'Best First'.
Re^2: define a hash-value, using hash-ref and a list of keys
by janssene (Initiate) on Oct 29, 2014 at 14:37 UTC
    Hi Roboticus, just wondering, my problem is that I can have situations where some keys can be not defined yet. so when filling in my value..$cf{$k1}{$k2}{$k3} = "$val", that $k2 and $k3 are not defined yet in the hash, for the given $k1. is there some specific command to create the ref for $cf{$k1}{$k2} before going further on $k3 ?
      Perl does this automatically, it's called autovivification.

      You only have an issue if you want to avoid it.

      update

      hmm thats the problem if you post from a mobile client without possibility to test...

      I'll update a working solution, though using Data::Diver should help already.

      update

      use warnings; use strict; use Data::Dumper; my @keys="a".."d"; my %hash=(); my $href=\%hash; my $lastkey= pop @keys; for my $key (@keys) { $href = $href->{$key} //= {} ; } $href->{$lastkey} = ""; print Dumper \%hash;
      --->
      $ perl dive.pl $VAR1 = { 'a' => { 'b' => { 'c' => { 'd' => '' } } } };

      update
      fixed bug

      Cheers Rolf

      (addicted to the Perl Programming Language and ☆☆☆☆ :)

        Hi Rolf, this is what I needed... having an older perl-version,I used for my $key (@keys) { $href =  $href->{$key} = {} unless defined $href->{$key};} is this notation {} having a specific usage or name ? Anyway, many thanks for the suggestion !!!

      janssene:

      Yes, I've botched that in my original answer. I've fixed it, though. (I also notice that LanX's repair is cleaner than mine. I need to start using the //= operator more often.

      ...roboticus

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