|
perldata - Perl Data Types
Part:
1
2
3
This chapter describes:
- Three built-in data types: scalars, arrays, and associative arrays.
- How to construct scalar objects.
- How scalar objects are interpreted in operations.
- How to construct list objects.
Data Types and Variables
Perl has three built-in data types: scalars, arrays, and associative arrays.
1. Scalar - A data type representing a single numeric value
or a string of characters. A scalar object can be assigned to a scalar
variable with an identifier prefixed with $: $identifier.
2. Array - A data type derived from scalar representing an ordered list
of scalars indexed by numbers, starting with 0.
An array object can be assigned to an array variable with an identifier
prefixed with @: @identifier.
3. Associative Array - A data type derived from scalar representing
an unordered list of scalars indexed by
their associated string keys. Associative arrays are also called hashes.
A hash object can be assigned to a hash variable with an identifier
prefixed with %: %identifier.
Like in many other programming languages, an identifier in Perl is a string
beginning with a letter or underscore, and containing letters, underscores, and digits.
Variables for different data types are in different name spaces.
You could use the same variable identifier for a scalar, an array, or a hash.
Scalar Value Constructors
Scalar value constructors are used to construct scalar objects. There are two types
of scalar value constructors: numerical literals and string literals.
Numerical literals are specified in integer and floating point formats as in the
following examples:
1
8.8
1e-1
1e+50
String literals are usually specified in single or double quotes as in the
following examples:
'3.14'
'Herong\'s Notes'
"Hello world!\n"
Note that with single quotes, only allow two backslash substitutions: \'
and \\. With double quotes, all backslash substitutions are allowed.
Here is some examples
to help you understand better what are good or bad scalar value constructors:
1; # ok
8.8; # ok
9.9.9; # bad, not a numberic value
1e-1; # ok
1e+50; # ok
1.0d; # bad, no double floating point notation allowed
'3.14'; # ok
1a; # bad, need quotes
'hello'; # ok
'dir \\home\\herong'; # ok
'Herong's Notes'; # bad, need a backslash substitution \'
"Herong's Notes"; # ok
'Hello world!\n'; # ok, but \n is not a backslash substitution here
Once scalar objects are constructed, they can be used in scalar variable
assignment operations as the following examples:
$one = 1;
$x = 8.8;
$big = 1e+50;
$pi = '3.14';
$msg = 'hello';
$cmd = 'dir \\home\\herong';
$title = "Herong's Notes";
Of course, scalar objects can be used in many other operations. We will discuss them
in other chapters.
(Continued on next part...)
Part:
1
2
3
|