'Why do Perl variables need to start with $, %,@ (sigils)?

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?



Solution 1:[1]

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)).

Solution 2:[2]

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.

Solution 3:[3]

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.

Solution 4:[4]

  • Because Perl was intended to replace shell scripts, and variables in shell start with $.
  • To distinguish between scalars ($), arrays (@) and hashes (%).

Solution 5:[5]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Hare
Solution 2 Leonardo Herrera
Solution 3 Peter Mortensen
Solution 4 Peter Mortensen
Solution 5 Peter Mortensen