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

How to convert an array_ref:
$aref = ['a', 'b', 'c', 'd'];
Into an hash ref such as:
$href = { 'a' => { 'b' => { 'c' => { 'd' => 1 } } }, };

Replies are listed 'Best First'.
Re: Change array to tiered hashref - brain teaser
by ikegami (Patriarch) on Aug 08, 2008 at 00:43 UTC
    By using Data::Diver
    DiveVal($href, map \$_, @$aref) = 1;

    Update: The advantage of this method is that it doesn't destroy the previous contents of $href.

      Thanks for data::diver. It does work, and is simple to use. I like trying to solve things without modules if possible because you learn more that way.
Re: Change array to tiered hashref - brain teaser
by BrowserUk (Patriarch) on Aug 08, 2008 at 00:41 UTC
      BrowserUK, I follow lines 1-3 (except for the ";;"). But I'm not clear on that last statement. Should "pp" print out the hash reference like in your last line? I can't find documentation for that usage, and I can't make my the script print. "print Dumper($href);" works for me.
        (except for the ";;")

        Two adjacent semi-colons act exactly the same as a single semicolon. Effectively there is a blank statement (noop) between them.

        The difference is that my REPL accumulates what I type until I finish a line with ;; at which point it executes everything I've typed so far as a single chunk of code.

        Should "pp" ... "print Dumper($href);" works for me.

        pp is just another Dumper()-like routine from Data::Dump.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.
      BrowswerUk: That was very good solution, and exactly what I was looking for. I kept trying to figure out how transversing a hashref will work, and your example really helped.

      I was very puzzled by this, but it makes a lot of sense, and cleared up everything for me in terms of understanding data structure. I spent the entire day on this with some really weird results. Now I understand why.

Re: Change array to tiered hashref - brain teaser
by MidLifeXis (Monsignor) on Aug 08, 2008 at 01:49 UTC

    Use List::Util::reduce.

    reduce { ( {$b => $a} ) } (1, reverse( @{["one", "two", "three", "four"]})))

    --MidLifeXis

      MidLifeXis, Thanks for bring up that the array had to be reversed.