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?
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.
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.
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.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)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With