Re: Unknown level of hash

Andrew Pimlott <[email protected]>
Newsgroups gmane.comp.lang.perl.fun
Message-ID <[email protected]>
On Mon, Mar 28, 2005 at 03:06:41PM -0800, Zhuang Li wrote:
> Hi, given an array: @a = ('E1', 'E2', ..., 'En'); 
> 
> Is there an easy way, hopefully one liner, to do the following without a
> loop? If not, will Perl support this in Perl 6?
> 
> $hash->{E1}->{E2}->...->{En} = 1;

If you're feeling functional,

    ${fold_left(sub { \${$_[0]}->{$_[1]} }, \$hash, @a)} = 1;

To get the value back out:

    fold_left { $_[0]->{$_[1]}  } $hash, @a;

Here is fold_left:

    sub fold_left (&@) {
        my $sub = shift;
        my $acc = shift;

        for my $each (@_) {
            $acc = $sub->($acc, $each);
        }

        return $acc;
    }

(You should be able to write the first one as

    ${fold_left { \${$_[0]}->{$_[1]} } \$hash, @a} = 1;

but Perl complains for no reason I can see.)

Andrew
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.