Re: Unknown level of hash

Aaron Sherman <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <1112056409.7453.18908.camel@pps>
On Mon, 2005-03-28 at 18:43, Uri Guttman wrote:
> >>>>> "ZL" == Zhuang Li <[email protected]> writes:
> 
>   ZL> Hi, given an array: @a = ('E1', 'E2', ..., 'En'); 
>   ZL> Is there an easy way, hopefully one liner, to do the following without a
>   ZL> loop? If not, will Perl support this in Perl 6?
> 
> 
>   ZL> $hash->{E1}->{E2}->...->{En} = 1;

I'm not sure I see P6 as solving this problem (though it's just as easy
in P6 as P5). What you're asking for is:

        @a = ('E1', 'E2','En');
        $hash={};
                setmultihashvalue($hash,[@a],1);
                sub setmultihashvalue {
                        my $ref = shift;
                        my $keys = shift;
                        my $value = shift;
                        if (@$keys > 1) {
                                my $key = shift @$keys;
                                if ($ref->{$keys->[0]}) {
                                        $ref = $ref->{$key};
                                } else {
                                        $ref = $ref->{$key} = {}; #autoviv
                                }
                                return setmultihashvalue($ref,$keys,$value);
                        } else {
                                $ref->{$keys->[0]} = $value;
                        }
                }
        use Data::Dumper;
        print Dumper($hash);

-- 
Aaron Sherman <[email protected]>
Senior Systems Engineer and Toolsmith
"It's the sound of a satellite saying, 'get me down!'" -Shriekback
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.