Scalar variables
A scalar holds one single value, such as a number, a piece of text or a reference.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the $ sigil when using a scalar
- Using a variable without declaring it under use strict
- 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: