A.3 Scalar Values and Scalar VariablesA scalar value is a single item of data, such as a string, a number, or a reference. A.3.1 StringsStrings are scalar values and are written as text enclosed within single quotes, like so: 'This is a string in single quotes.' or double quotes, such as: "This is a string in double quotes." A single-quoted string prints out exactly as written. With double quotes, you can include a variable in the string, and its value will be inserted or "interpolated." You can also include commands such as \n to represent a newline (see Table A-3): $aside = '(or so they say)'; $declaration = "Misery\n $aside \nloves company."; print $declaration; This snippet prints out: Misery (or so they say) loves company. A.3.2 NumbersNumbers are scalar values that can be:
Complex (or imaginary) numbers, such as 3 + i , and fractions (or ratios, or rational numbers), such as 1/3 , can be a little tricky. Perl can handle fractions but converts them internally to floating-point numbers, which can make certain operations go wrong (Perl is not alone among computer languages in this regard): if ( 10/3 == ( (1/3) * 10 ) { print "Success!"; }else { print "Failure!"; } This prints: Failure! To properly handle rational arithmetic with fractions, complex numbers, or many other mathematical constructs, there are mathematics modules available, which aren't covered here. A.3.3 ReferencesPerl references are scalar values that contain a location in memory where some other Perl data can be found. Think of references as scalar values that point to other data, such as scalars like strings or numbers, or arrays, hashes, or subroutines. References are mainly used to:
To create a reference, prepend a Perl value, variable, or subroutine with a backslash. To save a reference, assign it to a scalar variable. You can refer to a string by preceding it with a backslash: \'A referenced string' and you make a reference to a number similarly: .1415925 These references may be saved in scalar variables, discussed next . A.3.4 Scalar VariablesScalar values can be stored in scalar variables. A scalar variable is indicated with a $ before the variable's name. The name begins with a letter or underscore and can have any number of letters , underscores, or digits. A digit, however, can't be the first character in a variable name. Here are some examples of legal names of scalar variables: $Var $var_1 Here are some improper names for scalar variables: var $var!iable Names are case-sensitive: $dna is different from $DNA . These rules for making proper variable names (apart from the beginning $ ) also hold for the names of array and hash variables and for subroutine names. A scalar variable may hold any type of scalar value mentioned previously, such as strings or the different types of numbers. |