PERL: variables (or should we say $variables)?

When you tutor computer programming, you must explain the use of variables.  Such is the next step of our PERL summer project.

To a computer, a value needs a name.  Computers (at this level) aren’t capable of changing context the way humans can; they need to be told what to do, and what to do it to, at every stage.

Here’s an example of the difference between humans and computers.  Suppose, for instance, you tell a grade 6 student the numbers 11 and 29, then ask them for the average.  The student will add the numbers, divide the sum by 2, then spontaneously say “The average is 20.”  If you ask the student to tell the original two numbers, they can; however, they realize that what you really want is the answer.

On the other hand, a computer needs to “identify” a value before it can do an operation to it.  Therefore, a computer program to find the average of 11 and 29 might proceed like this:

get the value of the first number:  call it number1

get the value of the second number:  call it number2

add number1 and number2; call the sum number3

divide number3 by 2; call the result theaverage

print out “The average is ” theaverage

In traditional programming, you name a variable first, then give it a value.  When you want the computer to manipulate that value, you refer to it by its variable name.  Planning a program, you don’t wonder what the answer will be; rather, you wonder how to explain to the computer what to do in order to find the answer.  Specifically, you need to tell it what steps to perform to which variables.  Actually working with the numbers is easy for a computer, once it has clear instructions.

Commonly, variable names are written as one word, even if they indeed contain more than one.  Therefore, thirdnumber might be a likely name for the third number referenced in a program; on the other hand, you might call it number3.  Digits can be used in variable names, but usually aren’t allowed as the first character.

In PERL, variable names are commonly given a dollar sign prefix; therefore, if you wanted to call a variable number3, you’d call it $number3.  The dollar sign prefix increases program readability for humans; it’s easy to track what’s happening with the variables, since they all start with $.  There are other reasons, as well, for the $ prefix on PERL variable names.

Next post, we’ll see some variables in action.  Enjoy your day:)

Source: Robert’s Perl Tutorial, by Robert Pepper.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Tagged with: , , , , ,

Leave a Reply