Reputation: 35077
Why do Perl variables need to start with different characters (sigils)?
Scalar variables start with $
Hashes start with %
Arrays start with @
Why are they like this?
Upvotes: 27
Views: 9577
Reputation: 8406
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.
Upvotes: 23
Reputation: 98388
From Natural Language Principles in Perl:
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.
Upvotes: 12
Reputation: 262474
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.
Upvotes: 2
Reputation: 37103
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.Upvotes: 68
Reputation: 47042
$
.$
), arrays (@
) and hashes (%
).Upvotes: 11
Reputation: 351476
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)).
Upvotes: 36