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

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

    0 讨论(0)
  • 2020-12-11 16:54

    I can think of one way that

    $x = myarray[1];
    

    is ambiguous - what if you wanted a array called m?

    $x = m[1];
    

    How can you tell that apart from a regex match?

    In other words, the syntax is there to help the Perl interpreter, well, interpret!

    0 讨论(0)
  • 2020-12-11 16:56

    I've just used

    my $x = myarray[1];
    

    in a program and, to my surprise, here's what happened when I ran it:

    $ perl foo.pl 
    Flying Butt Monkeys!
    

    That's because the whole program looks like this:

    $ cat foo.pl 
    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    sub myarray {
      print "Flying Butt Monkeys!\n";
    }
    
    my $x = myarray[1];
    

    So myarray calls a subroutine passing it a reference to an anonymous array containing a single element, 1.

    That's another reason you need the sigil on an array access.

    0 讨论(0)
提交回复
热议问题