Search code examples
perlarrayshashsigils

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


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 elements? In other words, assuming you have an array @myarray and a hash %myhash, why do you need to do:

$x = $myarray[1];
$y = $myhash{'foo'};

instead of just doing :

$x = myarray[1];
$y = myhash{'foo'};

Why are the above ambiguous?

Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl?

@var[0];
@var{'key'};
%var[0];
%var{'key'};

Solution

  • Slices aren't illegal:

    @slice = @myarray[1, 2, 5];
    @slice = @myhash{qw/foo bar baz/};
    

    And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not.