A variable is used by a program to store a value. In Perl, there are three different types of variables.
- Scalar – one value of either a number, a string, a dualvar, a reference or undef
- Array – a set of values of indexed values starting with position 0
- Hash – a set of key-value pairs
Scalars use $ in front of the variable name. Array use @ in front of the variable name. Hashes use % in front of the variable name.
#!/usr/bin/perl use strict; use warnings; my $pizza = "plain"; my @pizza = ("plain", "pepperoni", "supreme", "veggie"); my %pizza = ("plain" => 5, "pepperoni" => 7, "supreme" => 6, "veggie" => 4); print "The pizza I ordered is ", $pizza, "\n"; print "The second pizza on the menu is ", $pizza[1], "\n"; print "The restaurant has ", scalar(@pizza), " kinds of pizza\n"; print "The restaurant has ", scalar(keys(%pizza)), " kinds of pizza\n"; print "The restaurant has ", $pizza{"veggie"}, " of the veggie pizzas\n";
When you run this program, it will print this on the screen:
The pizza I ordered is plain The second pizza on the menu is pepperoni The restaurant has 4 kinds of pizza The restaurant has 4 kinds of pizza The restaurant has 4 of the veggie pizzas
Like in many other programming languages, arrays start at position 0 for the first element, position 1 for the second element, position 2 for the the third element, etc.
The function scalar() counts the total number of elements of a list.
The function keys() grabs the keys of a hash and puts it in a list.
When you want to grab a value from a hash, you put the key value in between curly braces.
It’s important to understand the context of which you are using variables. Is the variable in scalar context or list context?