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

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

提交回复
热议问题