Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 43 ยท Scalars and Operators

Scalar Variables

Learn Perl scalar variables: the $ sigil, my declarations, numbers and strings, undef, string interpolation, q and qq quoting, here-docs and naming rules.

A scalar is a single value: one number, one string, or one reference. Scalars are the basic building block of every Perl program. A scalar variable holds one of these values, and its name always starts with a dollar sign, $.

What makes Perl scalars unusual is that you do not declare a type. The same variable can hold 42, "hello" or 3.14, and Perl converts between numbers and strings as the situation requires. This lesson covers how to create scalars, the kinds of values they hold, how interpolation works, and the quoting operators that make strings pleasant to write.

Perl does not run on this site, so the Perl blocks are read-only with real output from Perl 5.42 shown below. The TryIts are Python stand-ins that act out the same ideas.

Sigils and my

A sigil is the punctuation character at the front of a variable name. It tells you what kind of variable it is.

Three sigils

Scalar One value, like $name.
Array A list, like @colors.
Hash Key and value pairs, like %ages.

This lesson uses only the dollar sign.

1 / 2

You declare a variable with my the first time you use it (this is what use strict and use warnings requires), then assign with =:

PERL
use v5.36;

my $name = "Ada";
my $age  = 36;
my $pi   = 3.14159;

say "$name is $age";
say "pi is $pi";
TEXT
Ada is 36
pi is 3.14159

Once declared, you refer to the variable by its full name, $name, with no my. To change it, just assign again: $age = 37;. You can declare without a value too, my $total;, and the variable starts as undef.

Numbers

Perl accepts several number notations. Underscores are ignored, so you can group digits for readability:

PERL
use v5.36;

my $big = 1_000_000;
my $hex = 0xff;
my $bin = 0b1010;
my $oct = 0o17;
my $sci = 1e3;

say "big=$big hex=$hex bin=$bin oct=$oct sci=$sci";
TEXT
big=1000000 hex=255 bin=10 oct=15 sci=1000

Perl prints numbers in decimal, whatever notation you used in the source. The 0o17 form for octal needs Perl 5.34 or newer; older code writes 017. Perl stores whole numbers as integers when they fit and otherwise as floating-point values. We cover arithmetic in Operators and Numbers.

Strings

A string is any text, from empty to very long. You write strings with quotes, and the kind of quotes you choose decides what Perl does inside them. Strings and numbers are interchangeable, so "10" and 10 are both valid inputs to arithmetic.

Double quotes interpolate

Inside double quotes, Perl replaces variable names with their values (interpolation) and understands escapes like \n, \t and \":

PERL
use v5.36;

my $name = "Ada";
my @a = (1, 2, 3);
my %h = (k => 'v');

say "Hello, $name";
say "arr: @a, first $a[0], last $a[-1], hash $h{k}";
say "Hello, ${name}s!";
say "Email: ada\@example.com";
say "Price: \$5";
TEXT
Hello, Ada
arr: 1 2 3, first 1, last 3, hash v
Hello, Adas!
Email: [email protected]
Price: $5

Notice three things:

  • Arrays interpolate with spaces between items, and $a[0] and $h{k} pick single elements.
  • Use ${name} to mark where a variable name ends. Without braces, "$names" would look for a variable called $names.
  • A literal @ or $ needs a backslash inside double quotes. An email address like [email protected] would otherwise try to interpolate an array named @example, which strict rejects.

Single quotes do not

In single quotes nothing is interpolated, and the only escapes are \\ and \':

PERL
use v5.36;

say 'Price: $5';
say 'Literal $name\n';
TEXT
Price: $5
Literal $name\n

Use single quotes for text that has dollar signs or backslashes, such as regular expressions and Windows paths.

q and qq

The operators q() and qq() are single and double quotes with a delimiter you choose. They save you from escaping quotes inside the text:

PERL
use v5.36;

my $name = "Ada";

say qq{He said "hi" to $name};
say q{Literal $name};
say q(It's easy);
TEXT
He said "hi" to Ada
Literal $name
It's easy

q behaves like single quotes and qq like double quotes. You can use any bracket pair, or any other punctuation, as the delimiter, so pick one that does not appear in the text.

Here-docs

For several lines of text, a here-document starts with <<"END" and runs until a line containing only END. Double-quoted here-docs interpolate:

PERL
use v5.36;

my $name = "Ada";
my $text = <<"END";
Name: $name
Status: active
END
print $text;
TEXT
Name: Ada
Status: active

Use <<'END' (single-quoted tag) for text with no interpolation.

An apostrophe trap

Perl once used the apostrophe as a package separator, so "$name's book" was read as the variable $name::s. In Perl 5.36 this prints a warning and an empty name. Perl 5.42 treats the apostrophe as plain text only when your code starts with use v5.42;. The safe way, on any version, is braces:

PERL
use v5.36;

my $name = "Ada";
say "${name}'s book";
TEXT
Ada's book
Python Stand-in: interpolation and quoting (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's f-strings and raw strings behave a lot like Perl's double and single quotes. The details differ (Python never interpolates arrays on its own), but the mapping is close.

undef

A scalar that has not been given a value holds undef, Perl's "no value". It is different from zero and from the empty string. You check it with defined:

PERL
use v5.36;

my $u;
say defined $u ? "defined" : "undef";

$u //= "default";
say $u;
TEXT
undef
default

The //= operator assigns only when the left side is undefined, a handy way to set defaults. In arithmetic or string context an undef is treated as 0 or "", but with use warnings Perl tells you about it. You will see more about this in Operators and Numbers.

Numbers and strings blur together

Perl decides what a value means from the operator, not from how you wrote it. The + operator wants numbers, and the . operator wants strings:

PERL
use v5.36;

say "10" + "20";
say "10" . "20";
say "5" x 3;
say "3 apples" * 2;
TEXT
30
1020
555
6

The first line adds, the second joins text, the third repeats the string "5" three times, and the fourth uses the leading 3 of "3 apples" and (with warnings on) prints Argument "3 apples" isn't numeric in multiplication (*). The upside is that you never need to convert input from a file by hand. The downside is that mistakes hide easily, so keep use warnings on.

Python Stand-in: the operator decides (Python)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In Perl, each of those operators picks its own interpretation of the same values. That is why Perl has separate operators for numeric and string comparison, which Operators and Numbers explains.

Naming variables

A scalar name starts with $, then a letter or underscore, then letters, digits and underscores. Names are case-sensitive: $Name and $name are different variables.

  • Prefer lowercase_with_underscores, such as $total_price.
  • Choose descriptive names; $count beats $c.
  • Avoid $a and $b. They are special variables used by sort, and my $a can cause confusing bugs.
  • Do not reuse a name in the same scope; Perl warns that the second my masks the first.

A scalar and an array can share a base name because the sigil makes them separate things: $items, @items and %items are three different variables. It is allowed, and best avoided.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which statement correctly declares a scalar variable with a value?

    A scalar starts with the $ sigil and is declared with my. The @ sigil would create an array.
  2. 2. What does say 'Hello, $name'; print?

    Single quotes never interpolate, so the dollar sign and the name stay as typed.
  3. 3. How do you write "[email protected]" inside double quotes so that it does not interpolate an array?

    A backslash before @ stops interpolation. Without it Perl would look for an array named @example, which strict rejects.
  4. 4. What does $x //= 5; do when $x is undef?

    //= assigns the right-hand value only when the left side is undefined.
  5. 5. What is the result of "10" . "20" in Perl?

    The dot operator joins strings. The + operator would add the values as numbers and give 30.

Summary

  • A scalar holds one value (number, string or reference); its name starts with $ and you declare it with my.
  • Perl converts between numbers and strings depending on the operator, and warns when a string is not fully numeric.
  • Double quotes interpolate variables and escapes; single quotes are literal; q and qq let you choose the delimiters; here-docs hold multi-line text.
  • Use ${name} to end a variable name, and escape @ and $ that should appear literally.
  • undef means no value; test it with defined, and give defaults with //=.

Next, work with text in Working with Strings.