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?

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.

People have already pointed out that you can have slices and contexts, but sigils are there to separate the things that are variables from everything else. You don't have to know all of the keywords or subroutine names to choose a sensible variable name. It's one of the big things I miss about Perl in other languages.

I see. So if you are programming on a monochrome terminal, and don't have an IDE with syntax highlighting, and are using several modules from CPAN, it increases code readability.
–
maxwellbJul 7 '09 at 16:21

1

No, IDEs and syntax highlighting have nothing to do with it. It's the reasons I listed in my answer.
–
brian d foyJan 8 '10 at 13:19