in reply to Hash initialization works, but why?

The short answer is that @array{1,2,3} is a hash slice, and therefore an array. You can tell it's a hash slice because the indexes are inside {curlies}. You can tell it's an array because it starts with an @.

It's rather like the whole beginner array-vs-array-item confusion that so many people encounter, at least briefly: if @x is my array, surely item 3 in @x should be @x[3] ?

But of course it's not, it's $x[3] because the item itself is a scalar.

In this case, even though we're retrieving from (or in your case assigning to) a hash, we're interacting with it in a list-centric way rather than a one-thing-at-a-time way.

So @x{...} refers to %x. It has nothing to do with @x at al, and also nothing to do with typeglobs.

The trick is to understand that the kind of brackets around the index ({} vs []) determine whether it's an array or hash that you're dealing with, not the symbol at the front, which only determines how many things you're dealing with in one operation.

Replies are listed 'Best First'.
Re^2: Hash initialization works, but why?
by ikegami (Patriarch) on Jun 04, 2008 at 23:09 UTC

    The short answer is that @array{1,2,3} is a hash slice, and therefore an array

    That's wrong. It a hash slice, and it produces a list. It's not an array. Very different.

      I admit, I've always thought that 'array' was just Perl's particular jargon for 'list'. Or maybe "Perl's data-structure for holding a list." If I write
      @foo = (1,2,3)
      then @foo is an array, while (1,2,3) is a list. Right?

      I find myself still confused on the distinction between an array and a list. Could you explain more?

      throop

        It gets more confusing (but then it gets more clear).

        @foo is an array

        Yes.

        while (1,2,3) is a list

        1, 2, 3 is a list. The parentheses have nothing to do with its listishness. The parentheses are there only so that the parser doesn't parse the whole expression as:

        (@foo = 1), 2, 3;

        ... as it would if there were no grouping parentheses. They indicate which list you want to assign.

        List and Array have very clear and distinct definitions in Perl.

        List is a type of value.
        Array is a type of variable.

        You can't take the length of a list.
        There's no such thing as a reference to a list.
        There's no such thing as a list in scalar context.

        Come to think of it, that's in the FAQ.

        One more tidbit. The variable @foo is an array, but the expression @foo evaluates to a scalar or a list, depending on context.
        my $num_elemens = @foo; # @foo evaluates to a scalar. my ($first, $second) = @foo; # @foo evaluates to a list.