www.fachtnaroe.ie



Web This site

(Test: CSS  HTML)

Perl - Part 14

[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

Task 018

Create the following program (called names01.pl) to read in 5 names:

  ...
  ...You should know what to enter as a program header here...
  ...


  print "\nEnter a name: ";
  $name1 = <STDIN>;
  chop $name1;
  print "\nEnter a name: ";
  $name2 = <STDIN>;
  chop $name2;
  print "\nEnter a name: ";
  $name3 = <STDIN>;
  chop $name3;
  print "\nEnter a name: ";
  $name4 = <STDIN>;
  chop $name4;
  print "\nEnter a name: ";
  $name5 = <STDIN>;
  chop $name5;
  $which_name = -1;
  while ($which_name != 0)
  {
    print "\nYou entered 5 names. Choose (1-5) to see a name or 0 to exit: ";
    $which_name = <STDIN>;
    chop $which_name;
    if ($which_name == 1)
    {
      print "=> $name1\n";
    }
    else
    {
      if ($which_name == 2)
      {
        print "=> $name2\n";
      }
      else
      {
        if ($which_name == 3)
        {
          print "=> $name3\n";
        }
        else
        {
          if ($which_name == 4)
          {
            print "=> $name4\n";
          }
          else
          {
            if ($which_name == 5)
            {
              print "=> $name5\n";
            }
          } # end of else 4
        } # end of else 3
      } # end of else 2
    } # end of else 1
  } # Curly bracket for while

The last program read 5 names manually into 5 variables. Ask yourself the following questions:

  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?
  4. What happens if the user requests to see name 17?

The answer to the last question is more straightforward. A loop to check for valid values can be added. Enter:


    if ( ($which_name >= 1) && ($which_name <= 5) )
    {

below the line:

    chop $which_name;

Then indent all the program except the last curly bracket by two extra spaces. Before the last remaining bracket, correctly indented enter:


    } # end of 1-5 section
    else
    {
      print "\nERROR - Bad Value Entered\n";
    } # end of error message

This takes care of the 4th question but leaves the other, more important 3.

  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?
  4. What happens if the user requests to see name 17?

Read on for a solution...

[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-16:13
back to top
Fachtna Roe, Senior College, Central Technical Institute, Clonmel, Ireland.