eWebProgrammer eweb  

Perl Variables  «Prev  Next»
Lesson 4Scalar context in Perl
ObjectiveContext in which a scalar is used determines its type.

Perl Scalar Context

As you learned in the previous lesson, scalar values can be either numbers or strings. In fact, the same value can be interpreted as either a number or a string, depending on the context of its use.
In Perl, scalars are effectively typeless; perl will freely convert its internal representation of the data as needed. When the context of an expression demands numeric data, perl will convert the scalar values to numeric; when the context demands string data, perl will convert the scalars to strings.
For example:
$x = 3;
# 3 is a  literal numeric value,
# so $x is numeric
$y = "4";
# "4" is a string because
# it's in quotes  

Now, if the variables are used in a numeric context, $y will first be converted to a number:
$z = $x + $y;
# $y is first converted to
# numeric, then the 
# sum is placed in $z

On the other hand, if they are used in a string context, $x is first converted to a string:
$z = join(':', $x, $y);

# $x is first converted to
# a string then, $z will
# be "3:4"

Perl Data Types

The data types of the various Perl operators will be covered in the next module.

Scalars Context - Quiz

Click the Quiz link below to take a brief multiple-choice quiz about scalars in context.
Then we will move on to discuss literal types and how they're specified.
Scalars Context - Quiz