Perl - Part 19

[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]

Saving your data

As you have learned through practical experience by now, whether in Word Processing, Spreadsheets or any other form of computer usage it is essential to be able to save your work; whether to continue your work at a later stage or to keep that work for future reference. In the next task you'll see how that is done in Perl.

Task 021

Create the file below. Copy the file names02.pl to names02a.pl then modify the text of the program as given.

When you run the program you'll be asked for the number of names specified by $max (which we are treating as a constant). After the program runs, you may cat the file names.txt to see that the names from the array @all_the_names have been written to the file.

The NAMESFILE is a file variable, or file handle, used to refer to "names.txt". This can be any other meaningful name, just as other variables can have any meaningful name we desire. It is normal in all programming languages to generate an internal 'handle' for an external file.

Why "names.txt"? Read the program. Look closely also at the structure of the three lines that write the data to the file; you're about to see the reverse!

Reading (or recovering) your data

There's not much point saving data to disk if we can't recover it later...

Task 022

Copy the file names02.pl to names02b.pl then modify the text of the program as given.

Note how the > in the first open becomes a < in the second program. This is intended to indicate the flow of information. Note also how in both cases the full array of names is referred to beginning with @. You can change the name of the file in which the data is stored by changing the $filename at the start of the program.

Note also the use of the -1 in the second program for the modification of the loop. This is present because arrays in some languages number their first element as 0, others as 1. In Perl it's 0. So when in the first loop we began at 1 it was for our convenience and understanding; in the second, the array is read according to the normal Perl rules.

To see the difference the -1 makes, rewrite the line without the -1 and run the program. This should show how the numbers generated by the loop need to match the numbers required by the array.

When both programs are completed print them and bring them to Fachtna with screen-captures or print-outs of the data generated by the program runs. Make sure your programs have suitable header sections.

Onwards...

[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