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

后端 未结 9 1925
爱一瞬间的悲伤
爱一瞬间的悲伤 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:53

    The sigil give you the return type of the container. So if something starts with @, you know that it returns a list. If it starts with $, it returns a scalar.

    Now if there is only an identifier after the sigil (like $foo or @foo, then it's a simple variable access. If it's followed by a [, it is an access on an array, if it's followed by a {, it's an access on a hash.

    # variables
    $foo
    @foo
    
    # accesses
    $stuff{blubb} # accesses %stuff, returns a scalar
    @stuff{@list} # accesses %stuff, returns an array
    $stuff[blubb] # accesses @stuff, returns a scalar
                  # (and calls the blubb() function)
    @stuff[blubb] # accesses @stuff, returns an array
    

    Some human languages have very similar concepts.

    However many programmers found that confusing, so Perl 6 uses an invariant sigil.

    In general the Perl 5 compiler wants to know at compile time if something is in list or in scalar context, so without the leading sigil some terms would become ambiguous.

提交回复
热议问题