Why do you need $ when accessing array and hash elements in Perl?

后端 未结 9 1906
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 16:22

Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elemen

9条回答
  •  暖寄归人
    2020-12-11 16:47

    In Perl 5 (to be changed in Perl 6) a sigil indicates the context of your expression.

    • You want a particular scalar out of a hash so it's $hash{key}.
    • You want the value of a particular slot out of an array, so it's $array[0].

    However, as pointed out by zigdon, slices are legal. They interpret the those expressions in a list context.

    • You want a lists of 1 value in a hash @hash{key} works
    • But also larger lists work as well, like @hash{qw}.

    • You want a couple of slots out of an array @array[0,3,5..7,$n..$n+5] works

    • @array[0] is a list of size 1.

    There is no "hash context", so neither %hash{@keys} nor %hash{key} has meaning.

    So you have "@" + "array[0]" <=> < sigil = context > + < indexing expression > as the complete expression.

提交回复
热议问题