Set Perl Variables

Often, you only need to use a variable to store a single text or numeric value. Such variables are referred to as scalar variables in Perl.

Note Whether the variable contains a text or numeric value does not matter to Perl; the variable is evaluated as either a text string or a number based on what you are trying to do. If you try to perform a numeric operation on a text string, Perl will look for any digits at the beginning of the text and use that value, or if no digits are found, 0. If you perform a text operation on a number, Perl will treat the number as a text string.

Scalar Variable Names

Perl scalar variables are prefixed by the dollar sign ($) character. In addition, all Perl variable names must follow these rules:

  • Variable names must contain only letters (a-z, A-Z), underscores (_), and numeric digits (0-9).
  • The first character of a variable name must be a letter (a-z, A-Z) or underscore (_).
  • Variable names are case-sensitive, so myvariable is not the same as MyVariable.

Some variable names are used by WebAssign. These variables are listed in the documentation.

In an <EQN> or <eqn> tag, include an assignment statement like the following:
$variable = value;

where variable is the variable name and value is the value to be assigned. The value can be either a single value or a Perl expression that results in a value.


The following example variable assignment statements should be inside an <EQN> or <eqn> tag.

# set $radius equal to 5
$radius = 5;

# calculate the $diameter
$diameter = $radius * 2;

# use the predefined variable $pi
$circumference = $diameter * $pi;

# use ** for exponentiation
$area = $pi * $radius ** 2;

# use quotes to enclose a text value
$message1 = 'The radius is ';

# concatenate strings as text with the period (.)
$message2 = $message1 . $radius;

# in double quotes, the value of a variable is substituted
$message3 = "The diameter is $diameter.";