Perl sigils
Perl gets quite a bad rap for being a 'write only language', this is in part due to perl's usage of sigils which are a concept most languages do not include.
Perl's sigils are a concept that beginners often have trouble with, here I will try to explain their usage, note that I am only dealing with perl 5 sigils as perl 6 changes things further.
What is a sigil?
Sigils in perl are 'funny characters' attached to the front of variables $
, @
and %
are the most common.
Basic sigil usage
At first they seem to relate to the type of variables:
my $scalar;
my @array;
my %hash;
scalars ($
) are used for singular variables; things like strings or integers.
arrays (@
) are used for plural variables; a collection of scalars.
hashes (%
) are used for mapping; scalar to scalar.
If this were true then sigils would be equivalent to "Hungarian notation", but this is not so as I try explain below.
Sigil examples
On read sigils are operators where they signify the quantity of values you get out of the variable:
my $foo = 1;
# print variable in scalar 'foo'
say $foo; # outputs 1
Simple so far, we write a scalar and we read a scalar.
Notice what happens when we deal with reading scalar quantities from plural types:
my @bar = (1, 2, 3);
# print second item in array 'bar'
say $bar[1]; # outputs 2
Above $bar[1]
is non-ambiguous as []
is an operator only ever used on arrays, and we use the scalar sigil $
as
we are reading out scalar quantities.
my %baz = ( a => 1, b => 2, c => 3 );
# print value stored in hash 'baz' under key 'a'
say $baz{c}; # outputs 3
Above $baz{c}
is also non-ambiguous as '{}' is an operator only ever used on hashes, and we use the scalar sigil $
as
we are reading out scalar quantities.
More interesting sigil usage
Things get more interesting with slices, that is when we start dealing with plural quantities
We can read in plural:
my @bar = (1, 2, 3, 4);
say @bar[1..3]; # outputs 234
We can also write in plural:
@bar[1..2] = ("hello", "world");
say @bar[1..2]; # outputs helloworld
In both of the cases above @bar[...]
is dealing with a plural quantity of values in the array @bar
.
And the same can be done with hashes:
my %baz = ( a=>1, b=>2, c=>3 );
say @baz{a,b}; # outputs 12
@baz{a,c} = ("hello", "world");
say @baz{a,c}; # outputs helloworld
Again in both the cases above @baz{...}
is dealing with a plural quantity of values in the hash %baz
.
Cheat sheet
On variable declaration a sigil is used to denote the quantity
of things we want to be able to store in the containers.
On read and write a sigil is used to denote the quantity
we are dealing with ("am I reading/writing multiple things").