www.fachtnaroe.ie



Web This site

(Test: CSS  HTML)

Perl - Part 15

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

Storing Multiple Values - Easily

The previous program in some ways raises more questions than it answers, especially about how to handle different amounts of data.

  1. What would need to be done to change the number of names from 5 to 3?
  2. What would need to be done to change the number of names from 5 to 10?
  3. Is there anyway of shortening the asking and responding section at the end?

At present the answer to questions 1 and 2 would be to include less or more variables, input and chop lines. This is possibly acceptable for smaller amounts of numbers, but what if we wish to accept 100 names? Or a thousand? That represents a lot of typing!

As for the third question, the indentation used for 5 names is probably confusing. It would quickly become unmanageable on larger quantities - possibly even before you reached a 10th name mentioned in point 2!

No computer language could exist and be popular if it had no mechanism for shortening this. Perl is no different. For the tidier and more efficient version of this task, we'll use arrays.

Enter this program, called names02.pl instead:

In this case we are using an array of variables. An array is a collection of variables with the same name. In this case the array is called @all_the_names. Notice how the symbol @ is used instead of $. When @ is used all the elements are being referred to. When $ is used only one element is being referred to. That's why in the program above $ is used; as we are referring to (or using) only one element at a time. But we identify each element by it's number in the array which we get from [$counter].

As the value of $counter changes with the loop, so to does the element of the array that we are using.

Best of all, by changing the initial value of $max=whatever_number_you_like; at the start you can make the program work for 3, 10 or 1000 names.

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: 20120108-17:04
back to top
Fachtna Roe, Senior College, Central Technical Institute, Clonmel, Ireland.