Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 743
joe Avatar asked Jul 07 '09 10:07

joe


People also ask

What do variable sigils indicate in Perl 5?

Perl 5 uses variant sigils: the symbol changes depending on the type being accessed. For example: my @num = (1, 2, 3); my $num = 25; say $num[1]; Here all three variables are different; Perl maintains a sub-namespace of scalars, arrays, hashes and subroutines (and more) for every global and lexical context.

What are Perl variables?

Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.


2 Answers

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.
like image 137
Rob Wells Avatar answered Oct 13 '22 00:10

Rob Wells


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

like image 38
Andrew Hare Avatar answered Oct 13 '22 00:10

Andrew Hare