Using Scalar Variables

This section describes how a scalar variable can be assigned with a scalar value. An unassigned scalar variable contains the (undef) value. The undef() function removes the assigned value from a scalar variable.

Scalar variables can be used in a Perl script under these rules:

• A scalar variable should be assigned with a scalar value constructor using an assignment operation. For example, \$price = 19.99.
• A scalar variable without any scalar value assigned is an undefined variable and contains a special value called, undef.
• The assigned value can be removed from a scalar variable using the undef() function.
• A scalar variable can be used in a numeric operation, where the value contained in the scalar variable will be interpreted as a number.
• A scalar variable can be used in a string operation, where the value contained in the scalar variable will be interpreted as a string.
• A scalar variable can be used in a Boolean operation, where the value contained in the scalar variable will be interpreted as TRUE or FALSE.

See the previous section for scalar value interpretation rules.

Here are some examples of scalar variable assignment operations with scalar value constructors:

```   \$one = 1;
\$x = 8.8;
\$big = 1e+50;
\$pi = '3.14';
\$msg = 'hello';
\$cmd = 'dir \\home\\herong';
\$title = "Herong's Notes";
```

Here is a Perl tutorial script on how to use scalar variables:

```#- ScalarVariable.pl
#
\$price;                             # Undefined
print(\$price, "\n");                # (blank)

\$price = 19.99;                     # Defined
print(\$price, "\n");                # 19.99

\$price = \$price * 80/100;           # In an arithmetic operation
print(\$price, "\n");                # 16.992

\$price = "Market price";            # Changed to a string value
print(\$price, "\n");                # Market price

\$price = reverse(\$price);           # In a function call
print(\$price, "\n");                # ecirp tekraM

\$shipping = 3.99;
\$price = \$price + \$shipping;        # Auto-converted to a number: 0
print(\$price, "\n");                # 3.99

undef(\$price);                      # Undefined again
print(\$price, "\n");                # (blank)
```

Here is the output of the tutorial script:

```19.99
15.992
Market price
ecirp tekraM
3.99

```