If you're writing a program that involves computation, you're going to come face to face with some basic programming concepts. This article, the first of a five-part series, will explain scalars, one of the basic ideas of programming in Perl. It is excerpted from chapter two of the book Beginning Perl, written by James Lee (Apress; ISBN: 159059391X).
The essence of programming is computation—we want the computer to do some work with the input (the data we give it). Very rarely do we write programs that tell us something we already know. Even more rarely do we write programs that do nothing interesting with our data at all. So, if we’re going to write programs that do more than say hello to us, we’re going to need to know how to perform computations, or operations on our data.
In this chapter, we will discuss several important basic ideas of programming in Perl:
Scalars: Single values, either numbers or strings.
Variables: A place to store a value.
Operators: Symbols such as + and – that operate upon data.
Reading data from the user: We will read from standard input, also known as the keyboard.
Types of Data
A lot of programming jargon is about familiar words in an unfamiliar context. We’ve already seen a string, which was a series of characters. We could also describe that string as a scalar literal constant. What does that mean?
By calling a value a scalar, we’re describing the type of data it contains. If you remember your math (and even if you don’t), a scalar is a plain, simple, one-dimensional value. In math, the word is used to distinguish it from a vector, which is expressed as several numbers. Velocity, for example, has a pair of coordinates (speed and direction), and so must be a vector. In Perl, a scalar is the fundamental, basic unit of data of which there are two kinds—numbers and strings.
A literal is value that never changes. The value 5 is a scalar literal—and is literally 5; it can never be 4. Perl has three types of scalar literals: integers (such as 5), floating point numbers (like 3.14159), and strings (for example “hello, world”). To put it another way, a literal is a constant—it never changes.
As opposed to a variable which is a piece of memory that can hold a scalar value. Variables are so named because the value stored within them can vary. For instance,$numbercan be assigned 5, and then later can be changed to the value 6. We will talk more about variables later in this chapter.