Why do Perl variables need to start with different characters?
Scalar variables start with
$
Hashes start with
%
Arrays start with
@
Why are they like this?
Why do Perl variables need to start with different characters?
Scalar variables start with $
Hashes start with %
Arrays start with @
Why are they like this?
This is because Perl uses sigils:
In computer programming, a sigil (pronounced /'sɪdʒ.ɪl/ or /'sɪg.ɪl/; plural sigilia or sigils) is a symbol attached to a variable name, showing the variable's datatype or scope. The term was first applied to Perl usage by Philip Gwyn in 1999 to replace the more cumbersome "funny character in front of a variable name". The name is based on the word meaning a magical symbol (see sigil (magic)).
$
.$
), arrays (@
) and hashes (%
).Not all of them do, some start with % (hashes) or with @ (arrays).
It is a design decision to mark them as variables and also denote their type.
Note that you can have both a $abc
and a %abc
.
Check out a tutorial on Perl variables.
When I started out using Perl it was explained to me that these characters were chosen because:
$
looked a bit like an 's' so that was for scalars,@
has an 'a' in the middle so that was for arrays, and%
was for hashes because it looked like a key-value pair divided by a slash.Several reasons are explained by Larry Wall et al in "Programming Perl":
Within any given namespace [...] every variable type has its own subnamespace, determined by the funny character. You can, without fear of conflict, use the same name for a scalar variable, an array, or a hash (or, for that matter, a filehandle, a subroutine matter, a label or your pet llama.)
[...]
Like most computer languages, Perl has a list of reserved words that it recognizes as special keywords. However, because variable names always start with a funny character, reserved words don't actually conflict with variable names.
http://www.wall.org/~larry/natural.html:
English uses number and word order, with vestiges of a case system in the pronouns: "The man looked at the men, and they looked back at him." It's perfectly clear in that sentence who is doing what to whom. Similarly, Perl has number markers on its nouns; that is, $dog is one pooch, and @dog is (potentially) many. So $ and @ are a little like "this" and "these" in English.