Perl 5's fundamental data type is the scalar, a single, discrete value. That value may be a string, an integer, a floating point value, a filehandle, or a reference--but it is always a single value. Scalars may be lexical, package, or global (globals) variables. You may only declare lexical or package variables. The names of scalar variables must conform to standard variable naming guidelines (names). Scalar variables always use the leading dollar-sign ($
) sigil (sigils).
A scalar variable can contain any type of scalar value without special conversions or casts, and the type of value stored in a variable can change:
Even though this code is legal, changing the type of data stored in a scalar is a sign of confusion.
This flexibility of type often leads to value coercion (coercion). For example, you may treat the contents of a scalar as a string, even if you didn't explicitly assign it a string:
You may also use mathematical operations on strings:
This string increment operation turns a
into b
and z
into aa
, respecting character set and case. While ZZ9
becomes AAA0
, ZZ09
becomes ZZ10
--numbers wrap around while there are more significant places to increment, as on a vehicle odometer.
Evaluating a reference (references) in string context produces a string. Evaluating a reference in numeric context produces a number. Neither operation modifies the reference in place, but you cannot recreate the reference from either result:
$authors
is still useful as a reference, but $stringy_ref
is a string with no connection to the reference and $numeric_ref
is a number with no connection to the reference.
To allow coercion without data loss, Perl 5 scalars can contain both numeric and string components. The internal data structure which represents a scalar in Perl 5 has a numeric slot and a string slot. Accessing a string in a numeric context produces a scalar with both string and numeric values. The dualvar()
function within the core Scalar::Util
module allows you to manipulate both values directly within a single scalar.
Scalars do not contain a separate slot for boolean values. In boolean context, the empty string (''
) and '0'
are false. All other strings are true. In boolean context, numbers which evaluate to zero (0
, 0.0
, and 0e0
) are false. All other numbers are true.
One other value is always false: undef
. This is the value of uninitialized variables as well as a value in its own right.
Hey! The above document had some coding errors, which are explained below:
- Around line 3:
-
A non-empty Z<>