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
  • ... Vladi Belperchinov-Shabanski
    • ... Alexandre Jousset
      • ... Суханов Вадим
        • ... Alexandre Jousset
  • ... Ton Hospel
    • ... Yitzchak Scott-Thoennes
  • ... Yitzchak Scott-Thoennes
    • ... Alexandre Jousset
      • ... Yitzchak Scott-Thoennes
        • ... Alexandre Jousset
  • ... Andrew Pimlott
    • ... Alexandre Jousset
      • ... Andrew Pimlott
        • ... Alexandre Jousset
          • ... Alexandre Jousset
            • ... Andrew Pimlott
  • ... Zhuang Li
    • ... Jeff Yoak
    • ... Markus Laire
    • ... Luke Palmer
  • ... Zhuang Li

Reply via email to