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
In Perl 5 you need the sigils ($ and @) because the default interpretation of bareword identifier is that of a subroutine call (thus eliminating the need to use & in most cases ).
This is valid Perl: @var[0]
. It is an array slice of length one. @var[0,1]
would be an array slice of length two.
@var['key']
is not valid Perl because arrays can only be indexed by numbers, and
the other two (%var[0] and %var['key']
) are not valid Perl because hash slices use the {} to index the hash.
@var{'key'}
and @var{0}
are both valid hash slices, though. Obviously it isn't normal to take slices of length one, but it is certainly valid.
See the slice section of perldata perldocfor more information about slicing in Perl.
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.
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.
The sigil provides the context for the access:
$
means scalar context (a scalar
variable or a single element of a hash or an array)@
means list context (a whole array or a slice of
a hash or an array)%
is an entire hashIn Perl 5 (to be changed in Perl 6) a sigil indicates the context of your expression.
$hash{key}
. $array[0]
. However, as pointed out by zigdon, slices are legal. They interpret the those expressions in a list context.
@hash{key}
worksBut also larger lists work as well, like @hash{qw<key1 key2 ... key_n>}
.
You want a couple of slots out of an array @array[0,3,5..7,$n..$n+5]
works
@array[0]
is a list of size 1. There is no "hash context", so neither %hash{@keys}
nor %hash{key}
has meaning.
So you have "@"
+ "array[0]"
<=> < sigil = context > + < indexing expression > as the complete expression.