in reply to Re: Common Perl Idioms
in thread Common Perl Idioms

The @foo{ @foo } = 0 .. @foo; seems very clever to me (not to mention useful), but being a bit of a newbie, I don't really understand how it works. Anyone care to enlighten me?

Replies are listed 'Best First'.
Re^3: Common Perl Idioms
by Eimi Metamorphoumai (Deacon) on Jul 27, 2004 at 14:55 UTC
    It's creating a hash named %foo using a hash slice built out of the elements in @foo. Then it's assigning to that slice the values 0 to (the number of elements). So if @foo = ('a', 'b', 'c'), you get
    @foo{'a', 'b', 'c'} = (0, 1, 2);
    which is itself just shorthand for
    $foo{'a'} = 0; $foo{'b'} = 1; $foo{'c'} = 2;
    (technically, @foo in scalar context returns a value one too large, so we're really mapping to (0,1,2,3), but the odd element gets ignored. It might be more proper to use $#foo there (the index of the last element, instead of the number of elements))
      Aaaaaaaah... That was clever. Thanks!
Re^3: Common Perl Idioms
by dragonchild (Archbishop) on Jul 27, 2004 at 14:52 UTC
    You want to look up hashslices. That's going to be the key.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested