Perl - Part 5
[home] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
Programming Component Continued
Create a file called adder.pl with this code in it:#!/usr/bin/perl
use Term::ReadKey;
print "Enter two numbers and I'll add them:\n";
print "First number: ";
$num1 = ReadLine;
print "Second number: ";
$num2 = ReadLine;
$sumof = $num1 + $num2;
print "The answer is: $sumof.\n";
Before you run the program using the command perl adder.pl you should be aware that there is more than one way to run a perl program. Up until now you have been told to issue the perl command before the name of the file containing the program. This invoked the perl interpreter, fed it your program and all went well. If you issue the command ls -l in the perl_progs directory you should see a list of the current files in that directory/folder. It will look a little like this:

chmod +x adder.pl
to allow the file to be executed directly. This is the preferred method of operation. You can now run the program by using the command
./adder.pl
to run the file directly. The ./ means "in this directory". Try issuing the command without the ./ and see the error message caused by its absence! When you run the program you should get output like this:

Variables
When working with data in a program it is normally necessary to store that data temporarily as the program runs. The data is stored in what are called variables. They are called variables because the contents of the variable can be changed as the program runs - the contents can vary. (There are also what are called constants; these as the name implies remain unchanged throughout the program.) In all programming languages there are several types of data variables, and very often you need to know about the data type before the program starts; this is because you have to pre-declare the variables before you can use them. Perl is more forgiving than this. There is no need to pre-declare variables: when you use them the computer makes storage space for them automatically. You also don't need to make an explicit statement of what type of data (numeric, text, etc) to be stored. Perl works that out and proceeds accordingly. This also is unusual - and easier - compared to other programming languages. In Perl the most significant aspect of data storage is the choice of:- a simple variable - known as a scalar
- an array - or collection of variables under one name
- a hash table where values are stored in pairs, each value being a link to the other
[home] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] [22] [23] [24] [25]
Last updated: 20131015-16:45