All scalar variables are introduced by the $ symbol. The actual name of the variable may include any of the characters in the ASCII set,
alpha (a-z, A-Z), numeric (0-9), and the underscore ( _ ) with the exception that the first character may not be numeric.
The $ symbol is used whenever the variable is referenced:
# initialize a scalar to a string
$food = "spaghetti";
# initialize an integer number
$quan = 4;
# initialize a floating-point number
$price = "2.49";
# initialize a mathematical result
$total = $quan * $price
# pass a scalar to print
print "$food\n";
# initialize one scalar from another
$meal3 = $food;
In the above example, the string spaghetti is a scalar value, as is the number 4. The result of the expression, $quan * $price, is also a scalar value.
Syntax for Perl Scalar Variable
In Perl, a scalar variable is used to store a single value, such as a number, string, or reference. The syntax for a scalar variable consists of a dollar sign ($) prefix followed by the variable name. The variable name starts with a letter or underscore, followed by any combination of letters, digits, or underscores.
Here is the general syntax for a Perl scalar variable:
$variable_name
Here are some examples of scalar variable declarations and assignments:
my $integer = 42; # Assigning an integer value
my $float = 3.14; # Assigning a floating-point value
my $string = "Hello!"; # Assigning a string value
my $array_ref = [1, 2, 3]; # Assigning a reference to an anonymous array
my $hash_ref = { # Assigning a reference to an anonymous hash
key1 => 'value1',
key2 => 'value2',
};
In the examples above, we use the my keyword to declare a new lexical scalar variable and assign a value to it. Lexical variables have a limited scope and are not accessible outside the block they are declared in. You can also use the our keyword to declare a package-level scalar variable or the local keyword for temporary localization of a global variable. However, using lexical variables with my is generally recommended for better encapsulation and to avoid unexpected side effects.
Scalar Definition
Any value that represents only one thing (that is, a single-dimensional value) is a scalar.
Perl Scalar Type - Quiz
Click the Quiz link below to take a short multiple-choice quiz on scalars.
Understanding the basic use of the scalar type will allow us to build on that knowledge in the next lesson by learning about the differences between numeric and string context. Perl Scalar Type - Quiz