Perl : Scalar variables

Article Index

  1. What is a scalar?
  2. Operations and Assignment
  3. Interpolation

Scalars, what are they?

A Scalar variable holds 1 single piece of data. They can hold both strings and numbers and are remarkable in that strings and numbers are completely interchangable. For example, the statement

$priority = 9;

sets the scalar variable $priority to 9, but you can also assign a string to exactly the same variable.

$priority = 'high';

Perl also accepts numbers as strings and can still cope with arithmetic and other operations quite hapily, like this:

$priority = '9'; $default = '0009';

In general variable names consist of numbers, letters, and underscores, but should never start with an underscore ( $_ is special, don't do it!) Perl IS case sensitive, so $a and $A are different.

Operations and Assignment

Perl uses all the usual C arithmetic operators:

$a = 1 + 2; # Add 1 and 2 and store in $a
$a = 3 - 4; # Subtract 4 from 3 and store in $a
$a = 5 * 6; # Multiply 5 and 6
$a = 7 / 8; # Divide 7 by 8 to give 0.875
$a = 9 ** 10; # Nine to the power of 10
$a = 5 % 2; # Remainder of 5 divided by 2 (or modulus)
++$a; # Increment $a and then return it
$a++; # Return $a and then increment it
--$a; # Decrement $a and then return it
$a--; # Return $a and then decrement it

and for strings Perl has the following among others:

$a = $b . $c; # Concatenate $b and $c
$a = $b x $c; # $b repeated $c times

To assign values Perl includes:

$a = $b; # Assign $b to $a
$a += $b; # Add $b to $a
$a -= $b; # Subtract $b from $a
$a .= $b; # Append (Concatenate) $b onto $a

Note that when Perl assigns a value with $a = $b it makes a copy of $b and then assigns that to $a. When you change $b it will not alter $a. If $b contained a reference to $a then changing $b would also change $a. References will be covered in a later tutorial

Interpolation

Observe the following code:

Example:

1.
2.
3.
$a = 'apples';
$b = 'pears';
print $a . ' and ' . $b;

Output:

apples and pears

It would be nicer to include only one string in the final print statement, try this:

Example:

1.
2.
print '$a and $b';
$a and $b

The single quote will print literally which isn't very helpful. Instead we use double quotes.

Example:

1.
2.
print "$a and $b";
apples and pears

Double quotes force interpolation of any codes, include interpreting variables. This is much nicer and easier to read then our original statement. Other codes that are interpolated include special characters such as newline and tab. The code \n is a newline and \t is a tab.


Published by: Thomas Penwell
Initially published on: June 16, 2011
Article last modified on: Thursday, January 26, 2012.

Home - Web Portfolio - Web site Tools - Database Design Service - Consulting
Web Design Service - Web Hosting Solutions - Service Rates - Rentals/Loaners
Client Login - Feedback Form - Promotions - Partners - Articles - Perl Scripts