Scalars



next up previous
Next: Arrays of Scalars Up: Data Types Previous: Data Types

Scalars

The scalar is the basic data type in Perl. A scalar can be an integer, a floating point number, or a string. Perl figures out what kind of variable you want based on context. Scalars variables always have a dollar sign ($) prefix. Therefore, a string assignment looks like this:

	$str = "hello world!";
not:
	str = "hello world!";

In Perl, an alphanumeric string with no prefix is (generally) assumed to be a string literal. Thus, the second statement above attempts to assign string literal "hello world!" to string literal "str".

Perl's string quoting mechanisms are similar to those of the Bourne shell. Strings surrounded in double quotes ("...") are subject to variable substitution. Thus, anything that looks like a scalar variable is evaluated (and possible interpolated) into a string. Strings inside single quotes ('...') are passed through basically untouched.

Perl variables do not have to be declared ahead of time. The are allocated dynamically. It is even possible to refer to non-existent Perl variables. The default value for a variable in a numeric context is 0 and an empty string in a string context. Perl has a facility for determining whether a variable is undeclared or if it is really is a zeroish value.

Perl variables are also typed and evaluated based on context. String variables which happen to contain numeric characters are interpolated to actual numeric values if used in a numeric context. Consider this code fragment:

$x = 4;       # an integer
$y = "11";    # a string
$z = $x+$y;
print $z,"\n";

After this code is executed, $z will have a value of 15.

This interpolation can also happen the other way around. Numeric values are formatted into strings if used in a string context. Numeric values do not have to be manually formatted as in C or FORTRAN. This type of interpolation takes place often when writing standard output. For instance:

$answer = 42;
print "the answer is $answer";

The output from this fragment would be ``the answer is 42''.

Note that integer constants may be specified in octal or hexadecimal as well as in decimal.

String constants may be specified by way of ``here documents'' in the manner of the shell. Here documents start with a unique string and continue until that string is seen again. For example:

$msg = <<_EOM_;
   The system is going down.
   Log off now.
_EOM_



next up previous
Next: Arrays of Scalars Up: Data Types Previous: Data Types