← Back to Perl Course | Chapter 2: Variables | Lesson 1 of 7

Scalar variables

A scalar holds one single value, such as a number, a piece of text or a reference.

In this page:

  1. Scalar variables

Scalar variables

Scalar variable names start with a dollar sign, and you declare them with my. A scalar can hold a number or a string, and Perl converts between them as needed. A scalar that has not been given a value is undef, which you can test with defined.

Note: The values 0, "0", "" (empty string) and undef are false; everything else, including "0.0" and "00", is true.

Example: Scalar variables

perl
use strict;
use warnings;

my $name  = "Ada";
my $age   = 36;
my $price = 9.99;
my $nothing;

print "$name is $age years old\n";
print "Price with tax: ", $price * 1.2, "\n";
print "nothing is ", (defined $nothing ? "defined" : "undef"), "\n";
print "0.0 is ", ("0.0" ? "true" : "false"), "\n";
print "0 is ", (0 ? "true" : "false"), "\n";

# Output:
# Ada is 36 years old
# Price with tax: 11.988
# nothing is undef
# 0.0 is true
# 0 is false
Common Mistakes
  1. Forgetting the $ sigil when using a scalar
  2. Using a variable without declaring it under use strict
  3. Assuming "0.0" is false
Chapter Summary
  • Scalars start with $
  • Declare them with my
  • A scalar holds one value
  • undef means no value and defined tests for it
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.