PERL / CHAPTER 01
Scalars and explicit comparison
IntermediateChoose numeric or string operations intentionally in a small Perl program.
By the end of this chapter
- Declare lexical scalar variables
- Distinguish numeric and string comparison
- Use warnings to expose suspicious conversions
The idea
Enter with basic variables and expressions understood. A Perl scalar can hold a number, a string, a reference, or an undefined value. A dollar sign names a scalar variable, and my introduces a lexical binding. Start examples with use strict and use warnings so misspelled variables and suspicious conversions are easier to notice. These checks support careful code but do not replace a clear data contract.
Operators select important parts of the interpretation. Numeric equality uses ==, while string equality uses eq. The dot operator concatenates strings; plus performs numeric addition. Comparing numeric-looking identifiers as numbers can erase meaningful formatting, such as a leading zero. Choose the operation from the domain: a quantity may need arithmetic, while an account code may need exact text equality.
use strict;
use warnings;
my $code = "07";
print(($code eq "7" ? "same" : "different"), "\n");
print($code + 1, "\n");different 8
String comparison preserves the leading zero distinction. Numeric addition interprets the numeric-looking string as seven before adding one.
Try it yourself
Compare two identifier strings exactly, then separately add two known numeric quantities.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING